Skip to content

Commit

Permalink
ToC insertion triggered by HTML comment (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
MichelBoucey authored Aug 30, 2023
1 parent e41a37e commit 2d2b12c
Show file tree
Hide file tree
Showing 6 changed files with 158 additions and 56 deletions.
7 changes: 4 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@

BUILD=go build -o dumber
MV=mv dumber ${HOME}/go/bin/dumber
MV=mv dumber ~/go/bin/dumber
VERSION=`grep -Po '\d*\.\d*\.\d*' main.go`

help:
@echo "Usage:"
Expand All @@ -16,7 +17,7 @@ clean:
rm -f test/*numbered-sections*

distclean: clean
rm -f dumber ${HOME}/go/bin/dumber
rm -f dumber ~/go/bin/dumber

install: build
${MV}
Expand All @@ -27,7 +28,7 @@ watch:
CompileDaemon -build "${BUILD}" -command "${MV}"

.PHONY: test
test: install
test: clean install
test/run
@echo

19 changes: 14 additions & 5 deletions ReadMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,36 @@

With `dumber` (you already use `git`, don't you?) you can *add* or *remove* to your Mardown files:

- section numbers to header sections. Works on hash sign only, so one can exclude HTML section tags as <H1>.
- section numbers to header sections. This works on hash sign only, so one can exclude HTML section tags, as <H1>, to stay unnumenbered.
- a table of contents with links on entries.

## 2. Installation
See an [example](./example.md).

## 1. Installation

Install `dumber` from Github:

```
go install github.com/MichelBoucey/dumber@latest
```

## 1. Usage
## 2. Usage

```
user@machine $ dumber -h
Usage: dumber [OPTION] FILE
-h Show help
-r Remove table of contents and section numbers from the .md file
-t Add a table of contents to the .md file (can not be combined with -r)
-r Remove section numbers and table of contents from the .md file
-v Show version
-w Write section numbers to the .md file (default to stdout)
```

To add a table of contents you have to add a line with the HTML comment below, where you want the table of contents to appear:

```
<!-- ToC -->
```

The table of contents will be written just after the HTML comment line. And you can add this comment line as many times as you want, if you are, like me, a big fan of tables of contents, or if the length of your document needs a second table of contents at its end.

5 changes: 3 additions & 2 deletions example.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
<H1>Lorem</H1>

<!-- ToC -->
- [1.](#1-lorem-ipsum-dolor) Lorem ipsum dolor
- [1.1.](#11-lorem-ipsum-dolor-sit-amet) Lorem ipsum dolor sit amet
- [1.2.](#12-an-est-malis-dignissim-interpretaris) An est malis dignissim interpretaris
Expand All @@ -22,7 +25,6 @@
- [3.1.](#31-cu-qui-delectus-detraxit,-te-qui-veri-diceret-admodum) Cu qui delectus detraxit, te qui veri diceret admodum
- [3.2.](#32-pro-copiosae-erroribus-theophrastus-ex) Pro copiosae erroribus theophrastus ex
- [3.3.](#33-ex-eum-luptatum-molestiae) Ex eum luptatum molestiae
<H1>Lorem</H1>

# 1. Lorem ipsum dolor

Expand Down Expand Up @@ -115,4 +117,3 @@ Pro copiosae erroribus theophrastus ex, has adhuc expetenda reprimique ne. Id se
## 3.3. Ex eum luptatum molestiae

Ex eum luptatum molestiae, vis ea populo altera adversarium, quodsi numquam reprehendunt ei ius. Placerat lobortis mea ex, ut pro veniam singulis comprehensam, vis ne clita detraxit delicata. Ad sit prima utamur singulis. Ut sanctus ornatus vel. Eu quod perfecto omittantur vis, ne eum facer pericula.

66 changes: 31 additions & 35 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,17 @@ import (

func main() {

version := "2.0.1"
version := "2.1.0"

var headerCounters [7]int
var headerLines []string
var isToCInsertionLine bool = false
var mdLines []string
var mdTmpFile *os.File
var newLine string
var mdLines []string
var pathSep string
var rewrittenLine string
var section string
var headerLines []string
var upperHeaderLevel int

switch runtime.GOOS {
Expand All @@ -62,7 +63,6 @@ func main() {

helpFlag := flag.Bool("h", false, "Show help")
removeFlag := flag.Bool("r", false, "Remove table of contents and section numbers from the .md file")
tocFlag := flag.Bool("t", false, "Add a table of contents to the .md file (can not be combined with -r)")
versionFlag := flag.Bool("v", false, "Show version")
writeFlag := flag.Bool("w", false, "Write section numbers to the .md file (default to stdout)")

Expand All @@ -73,7 +73,7 @@ func main() {
os.Exit(-1)
}

if len(os.Args) == 1 || len(flag.Args()) == 0 && *helpFlag == false || *removeFlag == true && *tocFlag == true {
if len(os.Args) == 1 || len(flag.Args()) == 0 && *helpFlag == false {
fmt.Println("See -h for help")
os.Exit(-1)
}
Expand All @@ -95,6 +95,7 @@ func main() {
log.Fatal(err)
}

tocInsertionLine := regexp.MustCompile(`^<!--\s+\bToC\b\s+-->\s*$`)
tocLine := regexp.MustCompile(`^\s*-\s\[[\d\.]*\]\(#\d*`)
headerLine := regexp.MustCompile(`^(#{1,6})\s+([\d\.]*)\s*(.*)$`)

Expand Down Expand Up @@ -125,28 +126,23 @@ func main() {

rewrittenLine = header + " " + section + " " + title

}

if *tocFlag {

headerLines = append(headerLines, rewrittenLine)

}

mdLines = append(mdLines, rewrittenLine)

if !*removeFlag {

for i := currentHeaderType + 1; i <= 6; i++ {
headerCounters[i] = 0
}

section = ""

headerLines = append(headerLines, rewrittenLine)
}

mdLines = append(mdLines, rewrittenLine)

} else if !tocLine.Match([]byte(line)) {

if tocInsertionLine.Match([]byte(line)) {
isToCInsertionLine = true
}

mdLines = append(mdLines, line)

}
Expand All @@ -158,7 +154,7 @@ func main() {

mdFileHandler.Close()

if *tocFlag {
if !*removeFlag && isToCInsertionLine {

firstHeaderLine := headerLine.FindStringSubmatch(headerLines[0])

Expand All @@ -173,19 +169,19 @@ func main() {
log.Fatal(err)
}

if *tocFlag {
for _, line := range mdLines {

for _, line := range headerLines {
_, _ = io.WriteString(mdTmpFile, line+newLine)

_, _ = io.WriteString(mdTmpFile, toToCEntry(upperHeaderLevel, headerLine, line)+newLine)
if !*removeFlag && isToCInsertionLine && tocInsertionLine.Match([]byte(line)) {

}
for _, hline := range headerLines {

}
_, _ = io.WriteString(mdTmpFile, toToCEntry(upperHeaderLevel, headerLine, hline)+newLine)

for _, line := range mdLines {
}

_, _ = io.WriteString(mdTmpFile, line+newLine)
}

}

Expand All @@ -198,32 +194,32 @@ func main() {

} else {

if *tocFlag {
for _, line := range mdLines {

for _, line := range headerLines {
fmt.Println(line)

fmt.Println(toToCEntry(upperHeaderLevel, headerLine, line))
if !*removeFlag && isToCInsertionLine && tocInsertionLine.Match([]byte(line)) {

}
for _, hline := range headerLines {

}
fmt.Println(toToCEntry(upperHeaderLevel, headerLine, hline))

for _, line := range mdLines {
}

fmt.Println(line)
}

}
}
}

func toToCEntry(u int, r *regexp.Regexp, l string) string {
m := r.FindStringSubmatch(l)
repeat := len(m[1]) - u
if repeat < 0 {
c := len(m[1]) - u
if c < 0 {
fmt.Println("Header level too low line : " + l)
os.Exit(-1)
}
return (strings.Repeat(" ", repeat) + "- [" + m[2] + "](#" + strings.ToLower(strings.ReplaceAll(m[2], ".", "")+"-"+strings.ReplaceAll(m[3], " ", "-")) + ") " + m[3])
return (strings.Repeat(" ", c) + "- [" + m[2] + "](#" + strings.ToLower(strings.ReplaceAll(m[2], ".", "")+"-"+strings.ReplaceAll(m[3], " ", "-")) + ") " + m[3])
}

func addSectionChunk(s *string, hc int, cht int, ht int) {
Expand Down
21 changes: 10 additions & 11 deletions test/run
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ function filesum () {

}

DUMBER=${HOME}/go/bin/dumber
DUMBER=~/go/bin/dumber
RIGHT_NUMBERED_SECTIONS_CHECKSUM=a60c33256a196cf50bc7b9b5f1d5927c
RIGHT_NUMBERED_SECTIONS_WITH_TOC_CHECKSUM=0132da341c3fe97028d8d44fd13f8a83
RIGHT_NUMBERED_SECTIONS_AND_TOC_CHECKSUM=9c643b5d4c36f83ec979fe513ab1f233

echo

Expand All @@ -36,25 +36,24 @@ else
echo "KO"
fi

# Numbering Markdown sections with toc test
${DUMBER} -t test/test.md > test/numbered-sections-with-toc.md
# Numbering Markdown sections and adding a table of contents test
${DUMBER} test/test-toc.md > test/numbered-sections-and-toc.md

echo -n "- Numbering Markdown sections and adding toc -> "
echo -n "- Numbering Markdown sections and adding ToC -> "

if [ "$(filesum "test/numbered-sections-with-toc.md")" == "$RIGHT_NUMBERED_SECTIONS_WITH_TOC_CHECKSUM" ]; then
if [ "$(filesum "test/numbered-sections-and-toc.md")" == "$RIGHT_NUMBERED_SECTIONS_AND_TOC_CHECKSUM" ]; then
echo "OK"
else
echo "KO"
fi

# Unnumbering Markdown sections and removing toc test
${DUMBER} -r test/numbered-sections-with-toc.md > test/unnumbered-sections-removed-toc.md
# Unnumbering Markdown sections and removing a table of contents test
${DUMBER} -r test/test-toc.md > test/unnumbered-sections-and-toc-removed.md

echo -n "- Unnumbering Markdown sections and removing toc -> "
echo -n "- Unnumbering Markdown sections and removing ToC -> "

if [ "$(filesum "test/unnumbered-sections-removed-toc.md")" == "$(filesum "test/test.md")" ]; then
if [ "$(filesum "test/unnumbered-sections-and-toc-removed.md")" == "$(filesum "test/test-toc.md")" ]; then
echo "OK"
else
echo "KO"
fi

96 changes: 96 additions & 0 deletions test/test-toc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<H1>Lorem</H1>

<!-- ToC -->

# Lorem ipsum dolor

## Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, invenire expetendis id has. Et offendit appareat torquatos pro. Sed scaevola erroribus gubergren eu. Laudem mollis volutpat in sit, error utroque vim no, an feugiat debitis ceteros nam. Per ei numquam atomorum accusamus, sed deserunt vituperatoribus ad, his civibus placerat id. Sanctus concludaturque et eum, zril dolor an per.

## An est malis dignissim interpretaris

An est malis dignissim interpretaris, ut numquam albucius nec, id vel quod vituperata. Has ad quot eripuit, veri similique nam ei. Mel ei sumo omnis nulla, labores phaedrum temporibus mea ei. Ut vim nominati elaboraret, movet veniam repudiandae at usu. Eu mea eros doming prodesset.

# Sea molestie

## Sea molestie suavitate id

Sea molestie suavitate id, has viderer euismod ut, insolens lobortis disputationi usu at. Has nostrud disputationi at. Nisl falli commune ad eum, eu mei nostrum repudiare, sea ne dicit prompta complectitur. Eos ad epicurei praesent, audire graecis theophrastus pri ex. Vis cu case temporibus, vis in eius graecis abhorreant.

### Ad sea wisi iusto definitionem

Ad sea wisi iusto definitionem. Ex clita alienum appetere quo, per dicta solet euismod ex. Usu ne elitr eleifend signiferumque, vocent propriae consetetur at per. Eos ei eros alterum. Te nostro oblique pri, enim invidunt definitiones at his.

#### No laboramus ullamcorper eum

No laboramus ullamcorper eum, at impedit officiis vim. Stet molestiae disputationi eum te. Et duo nisl iuvaret mentitum, eam eu modo feugait rationibus. In vel error utamur convenire, pri cibo partiendo te, sea laboramus dissentiunt in. Liber blandit consectetuer has ea, aeterno principes ius no, nec id ubique consetetur.

#### Ea vim case tempor

Ea vim case tempor, vis ut nonumes mentitum. Probo argumentum sadipscing in per, vis at quas summo. Summo feugait eligendi ad pri. Ex meis affert soluta qui, elitr mediocrem consetetur qui et. Sea eu doming mandamus. Ceteros fastidii adipisci mel cu. Ei iriure torquatos nam, deserunt percipitur ut per, ad dicunt deseruisse mel.

### Quo sale maluisset

Vix labores postulant percipitur te, homero inermis an mel. His ei natum aperiri.

Vim erat prima ocurreret ea, sea recteque democritum mediocritatem in. Vim no vidit eligendi atomorum. Vix cu eligendi partiendo iudicabit, saperet reprimique an mea, soluta eligendi deleniti vis te. Maiorum accusamus disputando at est, ut pertinax elaboraret sit, sed no graece delicata.

## Quo sale maluisset neglegentur at

Quo sale maluisset neglegentur at. Te vis quod fugit, mel an maiorum antiopam. Ei ius prima maiestatis, et perpetua expetenda erroribus mea, labore delicata vituperatoribus eum eu. Te movet mollis mea, ius error labores pericula cu.

## Eu fugit altera cotidieque nam

Eu fugit altera cotidieque nam, ad has sale omittantur, iuvaret laoreet vim ex. Ne vim suscipiantur concludaturque. At iisque perfecto theophrastus vel. Rebum quaestio ne qui, brute everti ius te. Ei singulis mediocrem mel. Nec quas reque accusamus ea.

### Vidisse percipit ei per

Vidisse percipit ei per, errem referrentur et eos. Sea bonorum legendos tincidunt cu. Pri ut sanctus delectus, te homero invidunt instructior eum. Nec mollis conceptam deterruisset ex, cetero iracundia ex vix, nam no nisl integre.

#### Et est repudiare conceptam

Et est repudiare conceptam, at mel essent veritus. At repudiandae theophrastus mei, munere tacimates vis cu. Blandit fabellas invidunt ea eum. Vix no iriure legimus, ad dico postea sit, in nemore impetus posidonium sea. Unum viris albucius qui te. Ea facete everti voluptua vis, ad meis blandit vel.

##### Ubique scriptorem qui in

Ubique scriptorem qui in, ei gloriatur democritum sed. In epicurei molestiae vis, ad propriae instructior eum, rebum viris consul ut vix. Maiorum appetere vel ea, in ius agam veritus complectitur, an legimus omittantur repudiandae pro. Ea natum pericula ius, dicat eleifend ei pri. Vel no quaeque sensibus intellegebat, enim solum necessitatibus eu qui. Meis mollis placerat vim ex, expetenda urbanitas vis in. Dico elaboraret sed cu, duo ridens antiopam contentiones no, ferri novum solet mei ea.

###### Eu percipitur efficiantur duo

Eu percipitur efficiantur duo. Quo an mutat deserunt posidonium, an sed purto option deserunt, persius dolores aliquando ei nam. Vix adipisci convenire dignissim eu. Nec adhuc dicam congue eu, et alterum urbanitas nec.

###### Cum eius dignissim ei

Cum eius dignissim ei, te quo summo nostrum. Ea mei omnes suscipit, qui ad ferri etiam. Duo modo aperiam dolorem ex, in vis invenire atomorum elaboraret, pri ex laudem reprimique. Ei mei labore corpora vulputate. Ex delenit accusam scripserit pro.

##### Ei dolores accusamus mnesarchum vel

Ei dolores accusamus mnesarchum vel. Ne sed stet nibh, et has graeco inciderint, minim electram eu eum. Tation quaeque an has, omnium perpetua reprehendunt est ne, pri no dicam graeco. Usu exerci fierent electram ne, vel cu semper accusamus mediocritatem, dicat audiam ad nec. Te quot veritus eos. Affert officiis adipisci ad est, stet assueverit usu ex.

#### Ut saperet mandamus mea

Ut saperet mandamus mea, ad regione voluptaria his. Sit ad nulla audire insolens, pri euripidis disputando id. Fugit fabellas constituam at usu, sit elit aeque invenire in. Mei malorum consequuntur et. Volumus omnesque posidonium pro an. Quo ut postea graeci dolores, ut sumo graecis mentitum qui.

## Id pri dolore dictas

Id pri dolore dictas. Recusabo imperdiet mea ei, diam nonumy partiendo sea cu. Ad qui tota aliquam, facete nostrum eu ius. Dicam invidunt ea vis. Et qui integre menandri, ne qui omnesque probatus principes. Vel possim praesent ut.

## Iudico laboramus id vix

Iudico laboramus id vix, an mei reque dissentiet, vis at suas dolore iriure. Ea pro praesent eloquentiam, eos at audiam constituto. Et cibo conceptam voluptatum usu, mea eros erat autem eu. Id quem insolens eum. At est adipisci corrumpit, cu sit vero definiebas.

# Cu qui delectus

## Cu qui delectus detraxit, te qui veri diceret admodum

Cu qui delectus detraxit, te qui veri diceret admodum. His ei etiam latine labitur, dolor delenit constituam et eum. Consetetur interpretaris eam cu. Eu prima nonumy vocent mel, ei his nisl nominati. Te periculis dignissim inciderint vel, in dicat possit admodum sed. Ut vel alia nominati, sit etiam bonorum ne.

## Pro copiosae erroribus theophrastus ex

Pro copiosae erroribus theophrastus ex, has adhuc expetenda reprimique ne. Id sea dicant ornatus rationibus. Mei falli delectus evertitur ex, qui hinc nostro ad. Ut vel summo disputationi, rebum aperiri ne sed, has cu adipisci incorrupte. Id aliquid maiorum pri. Usu aperiri sanctus referrentur et, qui cu dissentias voluptatibus.

## Ex eum luptatum molestiae

Ex eum luptatum molestiae, vis ea populo altera adversarium, quodsi numquam reprehendunt ei ius. Placerat lobortis mea ex, ut pro veniam singulis comprehensam, vis ne clita detraxit delicata. Ad sit prima utamur singulis. Ut sanctus ornatus vel. Eu quod perfecto omittantur vis, ne eum facer pericula.

0 comments on commit 2d2b12c

Please sign in to comment.