Skip to content
simonschnakePublic

About

Lualatex package that allows to use markdown inside latex.

Resources

Stars

3 stars

Watchers

1 watching

Forks

Repository files navigation

Mark2TeX

Mark2TeX lets me write scientific material in Markdown and use LaTeX wherever I need it. The same Lua converter supports two ways of working.

  1. Markdown chapters inside a LaTeX project. The main document controls the class, bibliography, layout, and chapter order. Each chapter can live in a Markdown file, with TeX equations, citations, commands, and environments alongside the prose.
  2. A PDF from a standalone Markdown file. The command-line tool supplies a consistent layout or uses a template of my choice. From one lecture source, I can build a handout and presentation slides. Both can have an instructor edition with teaching notes or solutions.

How it got here

I wrote the first version for my PhD thesis. It was a large LaTeX project, and I wanted to write each chapter as a Markdown file while keeping all the possibilities of TeX. Embedding Markdown in the existing document let me keep the preamble and the typesetting decisions I had already made. The first parser handled just the syntax my thesis needed. The LaTeX package markdown was an inspiration, though its design choices did not fit the way I wanted to write.

I kept using Mark2TeX after the thesis. Its Markdown support grew as I needed new constructs in real documents. The way I develop it has changed as well. I wrote the original thesis version myself. Since then, AI has written an increasing share of the code.

The CLI came later, when most of my everyday writing had become individual documents. I wanted to start with one Markdown file and get a consistently formatted PDF without setting up a LaTeX project each time. Lectures are the current focus of that workflow. I want to explain a derivation in the script, present it in stages on slides, and keep a solution in the instructor edition, while editing the shared equations and prose only once.

Compatibility and scope

I am currently the only user, so my day-to-day work shapes what gets built. There is no fixed roadmap. Other people's use cases could change the direction. I want to keep writing new LaTeX projects with Markdown chapters, so direct integration remains a core use case. My thesis is a concrete compatibility benchmark for the package. Lecture profiles and slide layout options are opt-in.

I use Mark2TeX daily and maintain automated parser, LaTeX, and CLI tests. Security has received less attention. Source files can contain executable TeX, and custom templates are complete LaTeX documents compiled with LuaLaTeX. I use this workflow for trusted inputs. Compiling a stranger's document calls for an isolated environment with restricted file access.

Usage and reference

LaTeX usage

With the package installed, put these two files in the same directory.

main.tex

\documentclass{article}
\usepackage{mark2tex}

\begin{document}

\mdinput{content.md}

\end{document}

content.md

# Introduction

This chapter combines **Markdown prose** with TeX math such as $E = mc^2$.

Build main.pdf with:

latexmk -lualatex main.tex

\mdinput{...} converts the given Markdown file to LaTeX and inputs the generated file via \input. Generated files are placed in the mark2tex/ directory by default.

For chapter-like files there is also:

\mdinclude{chapter.md}

This inputs the generated file via \include.

To compile only selected Markdown includes, use \mdincludeonly in the preamble with the same Markdown paths passed to \mdinclude:

\mdincludeonly{introduction.md,conclusion.md}

Like LaTeX's \includeonly, excluded files retain their auxiliary data. They are not converted or registered as inputs during that run. An empty \mdincludeonly{} excludes all \mdinclude files. \mdinput is unaffected.

Both \mdinput and \mdinclude register their Markdown source files with LuaTeX's recorder. Build tools such as latexmk can therefore detect Markdown changes from the generated .fls file and rebuild the document automatically.

Important: Mark2TeX requires LuaLaTeX. Other engines such as pdfLaTeX are not supported.

Install the LaTeX package

Run make or make dist to type-check the Teal sources, verify that the committed Lua matches them, run the Lua regression suite, and build the TeX Live archive. The build uses Teal 0.24.1 from your PATH or a compiler command supplied with TL=.... If tl is missing, the first build downloads the pinned Teal and argparse sources via LuaRocks into .luarocks/ and runs the compiler with texlua. Subsequent builds reuse that local copy.

make

This produces dist/mark2tex.tar.xz. The archive contains a TDS structure and an embedded tlpobj, so it can be installed directly with tlmgr:

tlmgr install --file dist/mark2tex.tar.xz

To check the archive without installing it, use:

make tlmgr-install-dry-run

The package installs mark2tex.sty and the CLI templates under tex/latex/mark2tex/, and the Lua implementation and the mark2tex command under scripts/mark2tex/.

Overleaf

Overleaf usually does not allow project-local installation via tlmgr. For Overleaf there is therefore a separate bundle:

make overleaf-zip

This produces dist/mark2tex-overleaf.zip. That archive is not a TeX Live installation; instead it contains the files in a form that can be uploaded directly into an Overleaf project:

mark2tex.sty
mark2tex.lua
README.md
LICENSE

In Overleaf, mark2tex.sty and mark2tex.lua must live at the top level of the project. In the Overleaf menu, the compiler must be set to LuaLaTeX. After that, the package can be used like it is locally:

\usepackage{mark2tex}

\begin{document}
\mdinput{content.md}
\end{document}

Configuration

Configure Mark2TeX directly when loading the package:

\usepackage[
  citation=autocite,
  paren-citation=parencite,
  save-dir=generated-mark2tex,
  header={chapter,section,subsection,subsubsection,paragraph}
]{mark2tex}
Option Default Meaning
citation cite Command used for @key
paren-citation parencite Command used for [@key] and citation groups
save-dir mark2tex Directory for generated LaTeX files
header {section,subsection,subsubsection,paragraph,subparagraph} Heading commands, from level 1 upward
verbose false Log files when they are converted; use verbose or verbose=true to enable

Command names are written without a leading backslash. Load any package that provides your chosen citation commands separately. Enclose the comma-separated header list in braces; it replaces the entire mapping. Deeper headings use the last command in the list. Omitted or empty string options use their defaults.

The package no longer reads mark2tex_config.lua. Move existing settings into package options, using save-dir for save_dir, paren-citation for paren_citation, and a braced comma-separated list for header.

Compile Markdown to PDF

The mark2tex command is a texlua script, so it needs nothing beyond a TeX installation with latexmk, LuaLaTeX, Beamer, STIX Two and Latin Modern (plus Biber, biblatex and csquotes for --bibliography). It runs on macOS and Linux. From the repository checkout, link it into ~/.local/bin:

make install-cli          # PREFIX=/usr/local or BINDIR=... to link elsewhere
make uninstall-cli

The link points at mark2tex-cli.lua in the checkout, which finds mark2tex.sty, mark2tex.lua and templates/ beside it, so git pull also updates the command. The TeX Live archive installs the same script under scripts/mark2tex/. There, the CLI finds the package and its templates through kpathsea; link texmf-dist/scripts/mark2tex/mark2tex-cli.lua into your PATH as mark2tex, or run it with texlua.

mark2tex notes.md                                                      # notes.pdf
mark2tex lecture.md --format handout --writing-margin                    # lecture-handout.pdf
mark2tex lecture.md --format handout --instructor                        # lecture-handout-dozent.pdf
mark2tex lecture.md --format slides                                      # lecture-slides.pdf
mark2tex lecture.md --format slides --dozent                             # lecture-slides-dozent.pdf
mark2tex lecture.md --format slides --speaker-notes                      # lecture-slides-speaker-notes.pdf

Pass -o path/to/file.pdf to choose a destination. Relative TeX graphics paths are resolved from the Markdown file's directory. Use --title, --author, and --date for metadata. The author and date default to empty. With the built-in template, text and handout builds support --paper a4|letter, --toc, and --numbered. Handouts and slides accept --slide-level (default 2). Slides also accept --h1 section|frame|hide and --speaker-notes. Use --instructor or its alias --dozent in any format to select the instructor edition and add -dozent to the default filename.

Mark2TeX converts Markdown citations into LaTeX citation commands. To resolve them, pass a .bib file; the CLI then loads biblatex, runs Biber, and prints the bibliography at the end (on a final frame for slides):

mark2tex notes.md --bibliography refs.bib --citation-style authoryear

--bibliography can be repeated. To use your standard library in every build, set MARK2TEX_BIBLIOGRAPHY once, for example in your shell profile; several files are separated by :. --bibliography adds to these files, and --no-bibliography ignores the variable for one build. The bibliography is only printed when the document cites something, and only cited entries are listed. --citation-style takes any biblatex style and defaults to numeric. A change to a .bib file triggers a rebuild, also in --watch mode.

For raw TeX learning blocks, the built-in templates define \begin{Lernblock}{Title} to begin a section or a slide. The starred form continues the previous section in text and handouts.

Every output PDF has its own build directory under $XDG_CACHE_HOME/mark2tex/builds/ (default ~/.cache/mark2tex/builds/). latexmk records every file a build reads, including the Markdown, images, templates, .bib files and Mark2TeX itself, and rebuilds only when one of them changes. An unchanged document is therefore not compiled again. Two commands building the same PDF at once are refused; different PDFs build in parallel.

Use --watch to build immediately and rebuild whenever one of those inputs changes. Stop watching with Ctrl-C.

A failed build keeps the previous PDF and prints the end of the LaTeX log and the build directory. --verbose streams the LaTeX output, and --log-file copies the log to a file of your choice.

Build directories whose source file is gone or that have not been used for 30 days are removed automatically. mark2tex --clean notes.md (with the same -o, --format and --instructor as the build) removes the directory of one PDF, and mark2tex --clean-all removes all of them except those in use. Earlier versions of the CLI were written in Python and kept their cache in .mark2tex-cache/ in the working directory; such folders are no longer used and can be deleted.

Settings in the Markdown file

Instead of repeating options on every call, put them in a block at the very top of the Markdown file, as in Pandoc:

---
title: "Lecture 5: Heat conduction"
author: Jane Doe
date: Winter term 2026/27
format: slides
bibliography: [sources/lecture.bib]
citation-style: authoryear
---

# Conduction

mark2tex lecture5.md then builds lecture5-slides.pdf with that title and bibliography. Options on the command line take precedence, so mark2tex lecture5.md --format handout builds the handout from the same file, and --instructor or --speaker-notes select a variant as before. The block accepts title, author, date, format, audience, paper, language, font-size, template, title-image, toc, numbered, writing-margin, no-footer, slide-level, h1, bibliography, no-bibliography and citation-style, with the same values as the options. Paths are relative to the Markdown file. bibliography adds its files to $MARK2TEX_BIBLIOGRAPHY and to any --bibliography.

The block reads a small part of YAML: key: value, quoted strings, true/false, lists as [a, b] or as - item lines, and # comments. The CLI reports a malformed block with its line and names keys it does not use, so a typo such as titel: does not go unnoticed. In --watch mode, a changed title or layout setting is picked up with the next build; a change that renames the PDF or switches the template needs a new --watch. \mdinput skips the block, so the same file also works as a chapter of a LaTeX project.

Standard templates

A template you use for many documents, with its own search paths, can be given a name. A standard template is a folder with a template.yaml in ~/.config/mark2tex/templates (or a folder listed in $MARK2TEX_TEMPLATES, separated by :):

# ~/.config/mark2tex/templates/lecture/template.yaml
description: Lectures in the house style
slides: ~/latex/house/slides.tex
handout: ~/latex/house/handout.tex
text: stix
texinputs:
  - ~/latex/house
  - ~/latex/shared//
fonts: [~/latex/house/fonts]
author: Jane Doe
title-image: ~/latex/house/cover.png

template: lecture in the front matter, or --template lecture, then builds each format with its file (stix is the built-in layout), adds texinputs to the TeX search path (a trailing // searches subfolders) and fonts to the font search path, and fills in any other key the document leaves open, with the same keys and values as the front matter. The command line comes first, then the document's front matter, then the template. Relative paths in template.yaml are relative to its folder. Paths may use environment variables as $NAME or ${NAME}. A search folder under an unset variable is left out, so a template can point to a checkout where one exists and rely on an installed TeX tree elsewhere: texinputs: [${HOUSE_STYLE}/tex/latex//]. --template also accepts the folder itself, and mark2tex --templates lists the standard templates with their descriptions.

A template can build on another with extends: NAME (or a folder, relative to its own): its own entries come first, and the other template fills in the rest, its search folders included. A variant for one lecture then needs only what differs:

extends: lecture
slides: wide-slides.tex

Several variants at once

--format and --audience (student or instructor) take several values, comma-separated or repeated, and so do format and audience in the front matter. One call then builds a PDF for every combination, in parallel, each with the usual name:

---
title: "Lecture 5: Heat conduction"
format: [handout, slides]
audience: [student, instructor]
toc: true
---
mark2tex lecture5.md   # lecture5-handout.pdf, lecture5-handout-dozent.pdf,
                       # lecture5-slides.pdf, lecture5-slides-dozent.pdf
mark2tex lecture5.md --format slides --instructor   # just lecture5-slides-dozent.pdf

--instructor is short for --audience instructor. Settings that do not apply to a format are left out there instead of failing: toc, numbered, writing-margin and paper for slides with the built-in template, and h1, speaker-notes and slide-level where there are no slides. A single PDF keeps the strict checks. -o and --log-file name one file, so they need a single variant. If one variant fails, the others are still built and the command exits with status 1. --watch watches every variant, and Ctrl-C stops them all; --clean removes the build files of every variant.

Use a complete LaTeX template

The commented examples show how a template can read CLI options and turn them into LaTeX settings. Both use the same sample Markdown.

Output Template CLI format
Text Article template text (default)
Lecture handout Article template handout
Lecture slides Beamer template slides

Run these commands from the repository root:

mark2tex examples/cli/beispiel.md --template examples/cli/text.tex --title "Wärmelehre"
mark2tex examples/cli/beispiel.md --template examples/cli/text.tex --format handout --title "Wärmelehre" --writing-margin
mark2tex examples/cli/beispiel.md --template examples/cli/vorlesung.tex --format slides --title "Wärmelehre"
mark2tex lecture.md --format slides --template path/to/lecture.tex \
  --title "Lecture 5" --title-image images/cover.png --dozent --speaker-notes

The UTF-8 .tex template supplies the document class, preamble, fonts, theme, and body. Paths passed to --template and --title-image are relative to the working directory. Title images can be PNG, JPEG, or PDF. Load the generated mark2tex-template.tex before using the interface. Insert the converted Markdown with \MarkTwoTeXContent inside the document body.

\documentclass[aspectratio=169]{beamer}
\input{mark2tex-template.tex}
\usepackage{mark2tex}
\providecommand{\SlideFooter}[1]{}
\MarkTwoTeXHideDozent
\ifMarkTwoTeXSpeakerNotes
  \setbeameroption{show notes on second screen=right}
\fi
\title{\MarkTwoTeXTitle}
\author{\MarkTwoTeXAuthor}
\date{\MarkTwoTeXDate}
\ifMarkTwoTeXHasTitleImage
  \titlegraphic{\includegraphics[height=1.5cm]{\MarkTwoTeXTitleImage}}
\fi
\begin{document}
\ifMarkTwoTeXHasTitle
  \begin{frame}\titlepage\end{frame}
\fi
\MarkTwoTeXContent
\end{document}
  • \MarkTwoTeXTitle, \MarkTwoTeXAuthor, and \MarkTwoTeXDate contain escaped text. \ifMarkTwoTeXHasTitle indicates whether --title was supplied.
  • \MarkTwoTeXFormat, \MarkTwoTeXSlideLevel, \MarkTwoTeXLanguage, \MarkTwoTeXPaper, and \MarkTwoTeXFontSize expose the CLI settings. Font size is empty by default. Load the template data before \documentclass if the class options depend on these settings.
  • \ifMarkTwoTeXDozent, \ifMarkTwoTeXSpeakerNotes, \ifMarkTwoTeXNoFooter, \ifMarkTwoTeXWritingMargin, \ifMarkTwoTeXNumbered, and \ifMarkTwoTeXTOC let the template apply those presentation choices.
  • \ifMarkTwoTeXHasTitleImage indicates whether --title-image supplied an image. Pass \MarkTwoTeXTitleImage to the template's image command.
  • \ifMarkTwoTeXHasBibliography is true when at least one .bib file is configured. \MarkTwoTeXBibliographySetup then loads csquotes and biblatex with --citation-style and adds the .bib files; call it in the preamble after babel. \MarkTwoTeXCitationStyle holds the style name. \MarkTwoTeXContent defines \MarkTwoTeXHasCitations when the document cites something, so wrap \printbibliography in \ifdefined\MarkTwoTeXHasCitations … \fi after the content.

The template applies layout flags itself. If the Markdown uses raw TeX environments such as Lernblock, define them in the template.

The Markdown and template directories are both searched for relative input files, with the Markdown directory first. Set TEXINPUTS for additional class, theme, or asset directories. Changes to the template, the files it includes, and the title image trigger a rebuild, also in watch mode.

Standalone conversion

The standalone texlua scripts/convert.lua INPUT OUTPUT_DIR entry point prints the generated TeX fragment path. It accepts optional Lua profile settings such as profile=slides slide_level=2. An explicit document_id keeps generated footnote label prefixes stable across source edits.

Lectures as handouts and slides

Both LuaLaTeX documents read the same Markdown file with \mdinput{lecture.md}. For an article handout, load \usepackage[profile=handout,slide-level=2]{mark2tex}. For Beamer slides, load \usepackage[profile=slides,slide-level=2]{mark2tex}. The standard conversion is the default. Direct Lua calls use profile and slide_level.

  • Unindented headings at the selected level start a titled slide. Higher-level headings create section title slides. Lower-level headings appear as subheadings within a slide. In handouts, header controls heading formatting.
  • A line of at least three hyphens with a blank line on each side starts a continuation slide. In handouts, it adds paragraph spacing.
  • A continuation slide started by a separator has no title. For a titled slide whose heading is omitted from the handout, put a heading at the slide level inside a slides block.
  • A standalone . . . paragraph creates a Beamer overlay. In handouts, the blocks appear in sequence.

Headings, separators, and pauses follow the conventions of Pandoc's Beamer output. A standard Markdown preview displays the pauses as three dots and the separators as horizontal rules.

The black hole example includes an A4 template and a 16:9 template. The shared style sets a 155 mm text column and 12.75 bp body type, with STIX Two fonts and Latin Modern Sans for titles. Run make -j2 latex-lecture to build and check the PDFs in tests/lecture/. The test uses LuaLaTeX, Beamer, STIX Two, and Poppler's pdfinfo and pdftotext.

Content visibility and top-level headings

Columns and figures

Wrap two or more column divs in a columns div to set them side by side on slides. The script prints the columns in source order. A figure div such as ::: {.figure width=12em} accepts a raw tikzpicture, \input{diagram.tikz}, or a standalone Markdown image. Add a nested caption div at the end for an unnumbered script-only caption. The heat conduction example shows all fences.

Use ![Description](diagram.pdf){width=12em} for a standalone image with an explicit width. Widths in em scale with the surrounding type. An omitted width preserves the natural size. Both are capped at the available line width. The mark2tex package loads TikZ and adjustbox; load any drawing-specific TikZ libraries in your template.

Use ::: script for standard and handout output, ::: slides for slides, ::: instructor for the instructor edition, and ::: student for the regular edition. Close each block with a line containing only colons. Nested blocks require every enclosing condition to match. The attribute form ::: {.slides .instructor} combines both conditions in one block.

Use matching fence lengths and add one colon at each nesting level. An unmatched length or a nested fence that is no longer than its parent produces a warning. Missing and extra closing fences stop conversion with a line number. Mark2TeX filters these blocks before laying out slides or resolving footnotes. Excluded content takes up no space.

The blocks also work inside list items and blockquotes, indented like the rest of the item or behind the > marker. A list item that holds nothing but an excluded block disappears, bullet and all, so single points can appear in one edition only:

- For everyone
- ::: instructor
  Only in the instructor edition
  :::
- An exercise

  ::: instructor
  The solution, below the exercise.
  :::

Footers and speaker notes belong to a slide and stay at the top level; in a lecture profile, a footer or notes block inside a list or quote stops conversion.

Use --instructor or --dozent in the CLI. Direct Lua calls and package options use audience=instructor. The default is audience=student.

Use --h1 section|frame|hide to control top-level headings on slides. The default section follows the slide-level rule. frame uses the heading as the title of a regular content slide. hide drops the heading, keeps its content, and skips the slide break. Direct Lua calls and package options use h1. The handout preserves the heading levels of visible content.

## Energy balance

The balance follows from the first law of thermodynamics.

::: script
### Derivation

:::: instructor
Review the sign convention here.
::::
:::

::: slides
## Derivation
:::

For a closed system, $\Delta U = Q + W$.

Footers and speaker notes

::: footer
Handout section 5
:::

::: notes
Draw the pipe first.
:::

The first footer on a slide takes precedence. Notes can span multiple lines and appear in source order. In handouts, both annotations appear at the end of the current slide section. A Beamer theme can use \SlideFooter{…} to display footers. Define \providecommand{\SlideFooter}[1]{} to suppress them.

The colon fences and attribute notation follow Pandoc's Markdown syntax. Mark2TeX defines the meaning of the visibility and annotation classes. Earlier HTML comment directives are handled as ordinary comments.

Markdown and LaTeX in one source

A typical snippet:

# Motivation

The calibration follows @calibration and uses $\alpha < 0.1$ as threshold.

For the final selection we use:

- **nominal** reconstruction
- systematic variations with \cref{sec:systematics}
- the response model from [@response; @detector]

```tex
\begin{align}
  y &= f(x) \\
    &= x^2 + \alpha
\end{align}
```

This turns into LaTeX output such as:

\section{Motivation}

The calibration follows \cite{calibration} and uses $\alpha < 0.1$ as threshold.

For the final selection we use:

\begin{itemize}
\item \textbf{nominal} reconstruction
\item systematic variations with \cref{sec:systematics}
\item the response model from \parencite{response, detector}
\end{itemize}

\begin{align}
  y &= f(x) \\
    &= x^2 + \alpha
\end{align}

HTML comments remain in the generated .tex source as % comments and do not appear in the PDF. Both single-line and multiline comments are supported:

<!-- This is a comment -->
<!--
TODO:
Complete this section later.
-->

Comments can also occur within text. Each comment line receives a % prefix, and following text resumes on a new source line so it stays visible. Markdown and LaTeX inside comments are not parsed. An unclosed comment extends to the end of the input. Comment syntax inside backtick code spans and fenced code blocks stays literal.

Supported Markdown subset

The current parser intentionally supports only a small, tested subset:

  • headings with #, ##, ###, ..., with an optional closing sequence (## Heading ##), and setext level-1 headings underlined with ===
  • horizontal rules with three or more -, *, or _ on their own line, optionally spaced (- - -)
  • paragraph detection for normal text
  • hard line breaks with a backslash at the end of a line
  • HTML comments (<!-- ... -->), preserved as LaTeX % comments
  • italics with *text* or _text_
  • bold with **text** or __text__; delimiters next to whitespace do not count, and underscores inside a word (snake_case_name) stay literal
  • strikethrough with ~~text~~
  • inline code with backticks, e.g. `code`; LaTeX special characters stay literal
  • inline links ([label](target)), reference links ([label][ref], [ref][], [ref] with [ref]: target), URL autolinks, and email autolinks
  • inline images (![alt](path), optionally {width=2em}), also by reference
  • backslash escapes for Markdown punctuation that TeX does not use: \*, \+, \<, \>, \|, \?, and \`
  • fenced code blocks with three or more backticks or tildes, indented by up to three spaces (removed from the content lines, as in CommonMark)
  • fenced tex blocks as raw LaTeX output
  • blockquotes with >
  • inline math with $...$ or \\(...\\)
  • display math with $$...$$ or \\[...\\]
  • pipe tables, including inline formatting and math inside cells
  • LaTeX commands such as \alpha, \cref{...}, or \textit{...}
  • unordered lists with -, *, or +; blank lines between items keep one list
  • ordered lists with 1., 1), or lowercase letters followed by a closing parenthesis and whitespace, as in a) First item. The first marker sets the starting number or letter (for example, 4. or c)). Subsequent items count consecutively. Switching between alphabetic and numeric markers at the same indentation starts a new list.
  • nested lists and block content in list items: lines indented further than the item's marker belong to the item and may hold further paragraphs, fenced code, blockquotes, tables, display math, and nested lists. The indentation up to the item's content column is removed. A marker indented further than its parent's marker always nests (1. a followed by - b). A line without indentation ends the list, unless it is a lazy continuation line (see below)
  • single citations such as @key
  • Pandoc-style citation groups such as [@key1; @key2], including locators such as [@key, p. 433]
  • referenced footnotes ([^name] with [^name]: ...) and inline footnotes (^[...])
  • raw LaTeX environments with \begin{...} and \end{...}
  • raw LaTeX environments with optional $$ ... $$ or \\[ ... \\] wrappers

The output is LaTeX-like:

  • headings are mapped by default to \section, \subsection, \subsubsection, \paragraph, and \subparagraph
  • @key becomes \cite{key} by default
  • [@key1; @key2] becomes \parencite{key1, key2} by default
  • [@key, p. 433] becomes \parencite[p. 433]{key} by default
  • lists become itemize or enumerate
  • blockquotes become LaTeX quote environments
  • pipe tables become full-width tabularx environments with wrapping cells and automatic compact/text column selection; delimiter colons preserve alignment
  • normal code blocks are emitted as verbatim
  • tex code blocks are emitted unchanged as LaTeX
  • $$...$$ is normalized to \\[...\\]; \\[...\\] is kept in that form
  • ampersands, percent signs, hash signs, and literal underscores in text are escaped for LaTeX, so 50%, C#, and snake_case print as written

Links

Load \usepackage{hyperref} in your document preamble when using Markdown links. Mark2TeX reports a package error if it is missing.

[Website](https://example.org/page?x=1&y=2#part)
[PDF](<materials/Selected readings.pdf>)
[Section](#grundlagen)
<https://example.org/a_b>
<a_b@example.org>

Inline labels support formatting, code, and inline math. Destinations stay opaque to Markdown parsing. Parentheses may be balanced or escaped; angle brackets allow spaces in a destination. Optional quoted or parenthesized titles are parsed but do not appear in the output. URI spaces become %20; local file paths retain their spaces. A target beginning with # refers to an existing LaTeX label through \hyperref.

Give a heading an explicit link target with a trailing Pandoc-style ID:

See [Grundsätze der Anwendung](#grundsaetze-der-anwendung).

## Grundsätze der Anwendung {#grundsaetze-der-anwendung}

## Instructor example {#example .slides .instructor}

The visibility classes .slides, .script, .instructor, and .student use the same conditions as fenced divs. All listed conditions must match. They select the heading and its content through the next heading of equal or higher rank (exclusive), within the same div, list item, or blockquote. IDs and classes also work on supported setext headings. Use an explicit ID beginning with an ASCII letter or digit and continuing with letters, digits, underscores, periods, colons or hyphens. Choose a unique ID and ensure the target is visible in each edition that includes the link.

Reference links use a definition on its own line, anywhere in the file (including blockquotes and footnotes):

See the [project page][site] or simply [site].

[site]: https://example.org "Optional title"

Labels match case-insensitively with whitespace collapsed; the first definition of a label wins. A definition must follow a blank line or another definition, so a paragraph line such as [Note]: see below is never swallowed, and it must fit on one line. An unused definition produces a link warning, because it is omitted from the output. Undefined references stay literal text.

Inline images are written with \includegraphics, scaled down to the line width if needed. Their paths must be local files without TeX special characters (%, #, {, }, \, ^, ~); remote images stay literal text. An image may be the label of a link. Nested links are unsupported. Bare URLs require angle brackets to become autolinks. Links inside code, math, and raw LaTeX arguments are left alone.

Footnotes

Use a named definition or write a short footnote directly in the text:

Text with a footnote[^note] and an inline note^[An *inline* footnote.].
Another reference to the same note[^note].

[^note]: A footnote with **formatting**, `code`, $x^2$, and @citation.
    Continue a line with four spaces or a tab.

    Indented paragraphs and lists are supported too.

Definitions may appear before or after their references. Identifiers are case-sensitive, contain no whitespace or brackets, and are scoped to one Markdown input file, including its blockquotes. Unused definitions are omitted; for duplicate definitions the first wins and a footnote warning is emitted. The first reference emits a LaTeX \footnote; later references use \footref with the same number. Compile twice to resolve repeated references. Numbering uses the document's normal LaTeX footnote counter.

Notes support inline formatting, code, math, citations, links, and raw LaTeX. Referenced definitions also support paragraphs and lists. Fenced code in a definition is rendered as literal \texttt text, with ordinary TeX whitespace, because a verbatim environment cannot be used inside a footnote argument. Links still require hyperref. Footnote markers work in paragraphs, list items, blockquotes, and pipe-table cells. Nested footnotes and footnotes in headings or link labels are unsupported: their markers are displayed literally and reported as warnings. Undefined references and unclosed markers also produce warnings; their carets are escaped for safe LaTeX output. Code, math, and raw LaTeX arguments are not scanned for footnote syntax. Direct \footnote{...} commands remain unchanged and use LaTeX syntax inside their arguments.

Mathematics

Mathematics is a Mark2TeX extension; CommonMark itself does not define math delimiters. The supported forms and their output are:

Input Context Output
$x^2$ inline text, headings, lists, blockquotes, and table cells unchanged
\\(x^2\\) inline text, headings, lists, blockquotes, and table cells unchanged
$$x^2$$ display block, including lists and blockquotes \\[x^2\\]
\\[x^2\\] display block, including lists and blockquotes unchanged
\\begin{align}...\\end{align} raw LaTeX block unchanged

Markdown syntax inside math is not interpreted. LaTeX sub-environments that do not open math mode themselves, such as aligned, cases, and matrix environments, remain inside the normalized \\[...\\] display block. A self-contained display environment such as align, gather, or equation is emitted as that environment alone, avoiding an invalid nested display mode. Display delimiters in pipe-table cells are kept literal and reported as warnings; inline math is supported there.

Unclosed, empty, or mismatched math delimiters are preserved literally and produce a math-delimiter warning during file conversion. Unclosed or mismatched LaTeX environments produce a latex-environment warning. These warnings include line and column when the position can be determined. A delimiter preceded by an odd number of backslashes is treated as escaped. Code spans, fenced code blocks, and tex blocks are never parsed as math.

Blockquotes

A blockquote is written by starting every quoted line with > (after at most three spaces):

> **Observations** → data → patterns → model → application to new cases
>
> A second line with *inline formatting*.

Mark2TeX removes the markers, parses the content as Markdown blocks, and wraps the complete block in a LaTeX quote environment. This supports paragraphs, tables, lists, fenced code, and nested blockquotes (> > ...), including the usual inline formatting and math. Tables use the available width inside the quote. Blank lines inside a blockquote must be written as > lines.

As in CommonMark, a line without the > marker (or without a list item's indentation) still belongs to the quote or item when it continues the paragraph the quote or item ends in, a lazy continuation line. This also reaches into nested lists and quotes. A line that starts a block of its own ends the quote or item instead: a list marker, heading, rule, fence, raw LaTeX environment, display math, ::: fence or HTML comment. To end a list or quote before a paragraph, leave a blank line:

- The first item
continues here, as part of the first item.

This paragraph follows the list.
> **Board:** Organize the results in two columns.
>
> | Data | Model |
> | --- | --- |
> | Input $x$ | Parameter $w,b$ |
> | Target $y$ | Prediction $\hat y=wx+b$ |

Robustness rules

Mark2TeX only transforms complete, unambiguous Markdown constructs. An underscore in ordinary text (for example snake_case) is printed literally (written as \_); italics require a matching closing underscore or asterisk. Likewise, an unclosed fenced code block or an unclosed \begin{...} environment is emitted as ordinary text instead of being partially converted. Paragraphs immediately before or after a list remain separate paragraphs.

Deliberately unsupported

Mark2TeX is not a full Markdown converter. The CommonMark conformance report shows, section by section, how many examples of the CommonMark spec Mark2TeX handles like the spec does; make test fails if one of them regresses. In particular, do not expect the following to work like they do in CommonMark, Pandoc, or GitHub Markdown:

  • HTML blocks and inline HTML other than comments
  • indented code blocks (four spaces of indentation are ordinary text, since LaTeX bodies and continuation lines are often indented)
  • setext headings underlined with ---; such a line stays a horizontal rule (or a slide break in lecture profiles)
  • backslash escapes that mean something in TeX: \#, \_, \$, \%, \&, \{, \} keep their (identical) TeX meaning, while \-, \., \~, \^, \[, \(, and \`{e} stay TeX commands (hyphenation, accents, math)
  • HTML entities such as &copy; (use the Unicode character)
  • hard line breaks with two trailing spaces
  • task lists
  • fully specified edge cases for nested inline elements (the emphasis rules are a simplified version of CommonMark's)

If you need such constructs, the preferred approach at the moment is usually direct LaTeX, for example as a tex code block or a raw LaTeX environment.

Examples of LaTeX-friendly Markdown files

Inline LaTeX is preserved:

The corrected energy is $E_\mathrm{corr}$ and the result is shown in
\cref{fig:energy-response}.

Citations can be written concisely:

The detector model follows @detector-note and the calibration strategy follows
[@calibration-paper; @run2-performance].

For a parenthetical citation with a page or section locator, place the locator after a comma. It is passed as the optional argument of \parencite:

The original proposal is discussed in [@Turing1950, p. 433].

Pipe tables accept the usual alignment markers in their delimiter row and can contain the supported inline Markdown and LaTeX syntax:

| Quantity | Value | Comment |
| :------- | :---: | ------: |
| Energy   | $E$   | **fit** |
| Events   | 42    | @sample |

This produces a tabularx spanning \linewidth, with left-, center-, and right-aligned cells respectively. Font size stays unchanged. mark2tex.sty automatically loads array, tabularx, and booktabs; standalone converter output requires these packages in your document preamble.

Column selection is automatic and includes the header: a column is compact if its maximum cell length is at most 18 characters and its average at most 10. Markdown formatting does not count toward length; Unicode characters count once. Math and raw TeX use source length as a conservative approximation.

In mixed tables, compact columns use wrapping p{...} cells. Their widths are computed from their longest cell and capped at half an equal column share of the usable width (after intercolumn padding). Text columns share the remaining space equally using X. If every column is compact, all columns use X, so there is always a flexible column and no unused width. There are no weighted text columns or per-table settings.

Tables use \toprule, \midrule, and \bottomrule, without outer column padding or a center wrapper. Paragraph spacing separates tables from nearby text. \linewidth also respects narrower containers such as minipages.

This handles ordinary prose by wrapping instead of scaling. Unbreakable words, URLs, or long formulas can still overflow, and very many columns can become too narrow. tabularx does not split tables across pages. For these cases, or for captions and custom widths, use a raw LaTeX table.

More complex LaTeX blocks can be written directly in Markdown:

```tex
\begin{table}[h]
\centering
\caption{Nominal binning}
\label{tab:binning}
\begin{tabular}{l|c}
\toprule
Layer & bins \\
\midrule
1 & 32 \\
\bottomrule
\end{tabular}
\end{table}
```

Raw environments without a code fence are also recognized:

\begin{align}
  p(x) &= p(z)\left.\dv{f^{-1}}{x}\right|_{x=x_0}
\end{align}

Development

Project layout:

  • src/mark2tex/ contains the Teal sources (*.tl), the only source of the implementation.
  • src/*.d.tl declare the types of the external Lua modules LPeg, LFS and MD5; src/mark2tex/issue.d.tl holds the warning interface shared by all parsers.
  • mark2tex.lua is generated from the Teal sources: one bundle that registers every mark2tex.* module and returns mark2tex.core. It is committed so the package, Overleaf and the CLI need no Teal, and git diffs hide its content.
  • mark2tex.sty integrates Mark2TeX into LuaLaTeX by loading that bundle.
  • tests/ contains fixture tests, unit tests, golden snapshots, and LaTeX tests.
  • scripts/ contains the bundler and development helpers.

How a Markdown file becomes TeX:

  1. front_matter blanks a metadata block, and comments replaces HTML comments with placeholders, keeping a map from lines to source lines.
  2. parse_blocks reads the text line by line. At each line start it tries the block rules in a fixed order; lines where none matches are paragraph text, which is split into setext headings, paragraphs and blank lines. Blockquotes and list items collect their lines (without the marker or indentation, with lazy continuation lines) and read them with the same parser, so their blocks know their source lines too.
  3. divs selects the visible content of ::: blocks, in containers as well.
  4. parse collects link and footnote definitions and parses the inline content of every block into a typed AST (nodes): raw blocks first, then blocks holding inlines.
  5. lecture arranges slides and handouts, and write turns the AST into TeX.

make parser-diff compares the raw blocks, warnings and TeX of the parser at a git revision (PARSER_BASE, default main) with the current one over every golden input, the CommonMark examples, a fuzz corpus and the Markdown files in PARSER_DIFF_EXTRA. PARSER_DIFF_MODE=tex compares only warnings and TeX, loose also ignores blank lines.

Edit the .tl files, never mark2tex.lua. Then regenerate the bundle and verify that it matches its sources:

make teal-gen
make teal-check

make teal-gen compiles each module into build/teal/ and combines them with scripts/bundle.lua.

Both targets use the pinned Teal compiler described in Install the LaTeX package. Compiler settings (include path, Lua 5.3 code for LuaTeX without compatibility shims) live in tlconfig.lua, which editors and the Teal language server also read.

Run regression tests:

make test

Besides the unit tests and fixtures, make test renders every Markdown file under examples/ and tests/ in six profile variants and compares the TeX with the snapshots in tests/golden/. After an intended output change, review the difference and accept it with:

make golden-update

Run individual fixtures:

lua tests/run.lua tests/header.test tests/lists.test

Test LuaLaTeX and the CLI, once from the checkout and once installed from the TeX Live archive (these need latexmk, Biber and Poppler):

make latex-smoke
make -j2 latex-lecture
make cli-texlua
make cli-dist-check

make coverage measures which lines of src/mark2tex/*.tl the unit, golden and a short fuzz run execute, without any extra dependency. It prints the lines never run per module, writes annotated listings to tests/tmp/coverage/, and fails below COVERAGE_MIN (99.5 percent). make coverage-cli does the same for the CLI in src/cli/ while running its end-to-end suite: a texlua shim first in PATH routes every run of the script, including the watch hooks, through the line hook. It fails below COVERAGE_CLI_MIN (98 percent).

GitHub Actions runs the Lua tests, Teal bundle check, coverage check, LuaLaTeX tests, and both CLI suites on pushes and pull requests. The weekly extended fuzz run uses 16,000 inputs and a seed based on the UTC date. Reproduce a reported seed with make fuzz FUZZ_SEED=<seed> FUZZ_JOBS=1.

The test runner uses luaunit if it is installed. If luaunit is missing, it falls back to a small built-in assertion runner so that parser and writer fixtures can still be checked.

Dependencies

At runtime, the project currently uses Lua modules for LPeg, filesystem access, and MD5:

  • lpeg
  • lfs
  • md5

A working LuaLaTeX installation is required for the LaTeX integration. luaunit is optional for tests.

About

Lualatex package that allows to use markdown inside latex.

Resources

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages