mktoc
(make table of contents) is a CLI tool written in Rust to generate Table of Contents in Markdown files. It can be hooked up to execute on file save with third-party extensions like “Run on Save” for VSCode.
Usage
CLI
mktoc provides a few options and has sensible default values, see below.
$ mktoc README.md
$ mktoc -m 4 -M 2 README.md
$ mktoc -h
USAGE:
mktoc [FLAGS] [OPTIONS] [file]
FLAGS:
-h, --help Prints help information
-s, --stdout If set will output to stdout instead of replacing content in file
-V, --version Prints version information
OPTIONS:
-M, --max-depth <max-depth> Maximum heading level [env: MKTOC_MAX_DEPTH=] [default: 6]
-m, --min-depth <min-depth> Minimum heading level [env: MKTOC_MIN_DEPTH=2] [default: 1]
ARGS:
<file> [default: README.md]
The Markdown file must contain the following HTML comment:
<!-- BEGIN mktoc -->
<!-- END mktoc -->
or optionally, it can contain a inline config
<!-- BEGIN mktoc {"min_depth": 2, "max_depth": 4, "wrap_in_details": true} -->
<!-- END mktoc -->
The ToC will be placed inside the comment.
clap.rs is used for CLI parameter setup and parsing which is a great library for handling CLI parameters in Rust.
Library
As a library mktoc
provides one main function: mktoc::make_toc()
. This function takes the file name and the min and max heading levels as arguments and returns a Result<String, ::std::io::Error>
.
There’s lots of text parsing and re-writing involved to get the heading levels right and build the Markdown menu. All of this can be found in the src/lib.rs file.
Building mktoc is a great exercise in file parsing. I use the tool everyday with the Run on Save plugin in VSCode to generate Table of Contents in README files, and I like the challenges it brings. Doing all parsing by myself instead of using a finished markdown parser is a great exercise.