or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-markdown2

A fast and complete Python implementation of Markdown with extensive extras support

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/markdown2@2.5.x

To install, run

npx @tessl/cli install tessl/pypi-markdown2@2.5.0

0

# markdown2

1

2

markdown2 is a fast and complete Python implementation of Markdown that translates easy-to-read, easy-to-write structured text format into HTML. It closely matches the behavior of the original Perl-implemented Markdown.pl while providing extensive customization through 25+ built-in extras (extensions) for enhanced functionality like syntax highlighting, tables, footnotes, header IDs, and many advanced features.

3

4

## Package Information

5

6

- **Package Name**: markdown2

7

- **Language**: Python

8

- **Installation**: `pip install markdown2` or `pip install markdown2[all]` (with optional dependencies)

9

- **Python Requirements**: Python 3.9+

10

11

## Core Imports

12

13

```python

14

import markdown2

15

```

16

17

For class-based usage:

18

19

```python

20

from markdown2 import Markdown

21

```

22

23

For specific components:

24

25

```python

26

from markdown2 import Markdown, MarkdownWithExtras, UnicodeWithAttrs, MarkdownError

27

```

28

29

## Basic Usage

30

31

```python

32

import markdown2

33

34

# Simple conversion

35

html = markdown2.markdown("**bold text** and *italic text*")

36

print(html) # <p><strong>bold text</strong> and <em>italic text</em></p>

37

38

# Convert a file

39

html = markdown2.markdown_path("document.md")

40

41

# With extras (extensions)

42

html = markdown2.markdown(

43

"```python\nprint('hello')\n```",

44

extras=["fenced-code-blocks", "code-friendly"]

45

)

46

47

# Reusable processor

48

markdowner = Markdown(extras=["footnotes", "tables", "header-ids"])

49

html1 = markdowner.convert(text1)

50

html2 = markdowner.convert(text2)

51

52

# Pre-configured processor with common extras

53

from markdown2 import MarkdownWithExtras

54

markdowner = MarkdownWithExtras() # includes footnotes, fenced-code-blocks

55

html = markdowner.convert(markdown_text)

56

```

57

58

## Architecture

59

60

markdown2 uses a processing pipeline with defined stages and an extensible extras system:

61

62

- **Core Functions**: `markdown()` and `markdown_path()` for simple conversions

63

- **Markdown Class**: Reusable processor with configurable options and extras

64

- **Extras System**: Modular extensions that hook into processing stages

65

- **UnicodeWithAttrs**: Enhanced string return type with optional metadata and TOC attributes

66

- **Processing Stages**: Ordered pipeline from preprocessing to final HTML output

67

68

## Capabilities

69

70

### Core Conversion Functions

71

72

Essential functions for converting markdown text and files to HTML, with support for various output formats and processing options.

73

74

```python { .api }

75

def markdown(

76

text: str,

77

html4tags: bool = False,

78

tab_width: int = 4,

79

safe_mode: Optional[Literal['replace', 'escape']] = None,

80

extras: Optional[Union[list[str], dict[str, Any]]] = None,

81

link_patterns: Optional[Iterable[tuple[re.Pattern, Union[str, Callable[[re.Match], str]]]]] = None,

82

footnote_title: Optional[str] = None,

83

footnote_return_symbol: Optional[str] = None,

84

use_file_vars: bool = False,

85

cli: bool = False

86

) -> UnicodeWithAttrs: ...

87

88

def markdown_path(

89

path: str,

90

encoding: str = "utf-8",

91

html4tags: bool = False,

92

tab_width: int = 4,

93

safe_mode: Optional[Literal['replace', 'escape']] = None,

94

extras: Optional[Union[list[str], dict[str, Any]]] = None,

95

link_patterns: Optional[Iterable[tuple[re.Pattern, Union[str, Callable[[re.Match], str]]]]] = None,

96

footnote_title: Optional[str] = None,

97

footnote_return_symbol: Optional[str] = None,

98

use_file_vars: bool = False

99

) -> UnicodeWithAttrs: ...

100

```

101

102

[Core Conversion](./core-conversion.md)

103

104

### Processor Classes

105

106

Reusable markdown processor classes for efficient batch processing and advanced configuration.

107

108

```python { .api }

109

class Markdown:

110

def __init__(

111

self,

112

html4tags: bool = False,

113

tab_width: int = 4,

114

safe_mode: Optional[Literal['replace', 'escape']] = None,

115

extras: Optional[Union[list[str], dict[str, Any]]] = None,

116

link_patterns: Optional[Iterable[tuple[re.Pattern, Union[str, Callable[[re.Match], str]]]]] = None,

117

footnote_title: Optional[str] = None,

118

footnote_return_symbol: Optional[str] = None,

119

use_file_vars: bool = False,

120

cli: bool = False

121

): ...

122

123

def convert(self, text: str) -> UnicodeWithAttrs: ...

124

125

def reset(self) -> None: ...

126

127

class MarkdownWithExtras(Markdown):

128

# Pre-configured with: footnotes, fenced-code-blocks

129

pass

130

```

131

132

[Processor Classes](./processor-classes.md)

133

134

### Text Processing Extras

135

136

Extensions that modify how text elements are processed, including line breaks, emphasis handling, and typography enhancements.

137

138

```python { .api }

139

# Key extras: breaks, code-friendly, middle-word-em, smarty-pants, strike, underline

140

extras = ["breaks", "smarty-pants", "strike"]

141

html = markdown2.markdown(text, extras=extras)

142

```

143

144

[Text Processing Extras](./text-processing-extras.md)

145

146

### Code and Syntax Extras

147

148

Extensions for enhanced code block processing, syntax highlighting, and developer-friendly features.

149

150

```python { .api }

151

# Key extras: fenced-code-blocks, highlightjs-lang, pyshell

152

extras = ["fenced-code-blocks", "code-friendly"]

153

html = markdown2.markdown(code_text, extras=extras)

154

```

155

156

[Code and Syntax Extras](./code-syntax-extras.md)

157

158

### Link and Reference Extras

159

160

Extensions for advanced link processing, auto-linking, and reference management.

161

162

```python { .api }

163

# Key extras: link-patterns, link-shortrefs, markdown-file-links, nofollow

164

link_patterns = [(re.compile(r'bug #(\d+)'), r'http://bugs.example.com/\1')]

165

extras = {"link-patterns": link_patterns}

166

html = markdown2.markdown(text, extras=extras)

167

```

168

169

[Link and Reference Extras](./link-reference-extras.md)

170

171

### Structure and Layout Extras

172

173

Extensions for enhanced document structure including tables, footnotes, headers, and table of contents generation.

174

175

```python { .api }

176

# Key extras: tables, footnotes, header-ids, toc, html-classes

177

extras = ["tables", "footnotes", "header-ids", "toc"]

178

html = markdown2.markdown(text, extras=extras)

179

# Access TOC: html.toc_html

180

```

181

182

[Structure and Layout Extras](./structure-layout-extras.md)

183

184

### Special Content Extras

185

186

Extensions for specialized content types including mathematical expressions, diagrams, and interactive elements.

187

188

```python { .api }

189

# Key extras: latex, mermaid, wavedrom, spoiler, admonitions, alerts

190

extras = ["latex", "mermaid", "admonitions"]

191

html = markdown2.markdown(content, extras=extras)

192

```

193

194

[Special Content Extras](./special-content-extras.md)

195

196

## Types

197

198

```python { .api }

199

class UnicodeWithAttrs(str):

200

"""Enhanced string return type with optional attributes."""

201

metadata: Optional[dict[str, str]] # From 'metadata' extra

202

toc_html: Optional[str] # From 'toc' extra

203

204

class MarkdownError(Exception):

205

"""Base exception for markdown processing errors."""

206

pass

207

208

# Type aliases

209

SafeMode = Literal['replace', 'escape']

210

ExtrasDict = dict[str, Any]

211

ExtrasParam = Union[list[str], ExtrasDict]

212

LinkPatterns = Iterable[tuple[re.Pattern, Union[str, Callable[[re.Match], str]]]]

213

```

214

215

## Constants

216

217

```python { .api }

218

__version__: str # Package version (e.g., "2.5.4")

219

__version_info__: tuple[int, int, int] # Version tuple (e.g., (2, 5, 4))

220

__author__: str # "Trent Mick"

221

DEFAULT_TAB_WIDTH: int # 4

222

```

223

224

## Command Line Interface

225

226

```python { .api }

227

def main(argv: Optional[list[str]] = None) -> None:

228

"""CLI entry point for markdown2 command."""

229

pass

230

```

231

232

The package provides a `markdown2` console script when installed via pip.

233

234

**Basic Usage:**

235

236

```bash

237

# Convert from file to stdout

238

markdown2 document.md

239

240

# Convert from stdin

241

echo "**bold text**" | markdown2

242

243

# Convert to file

244

markdown2 document.md --output document.html

245

246

# Convert multiple files

247

markdown2 doc1.md doc2.md doc3.md

248

```

249

250

**Command Line Options:**

251

252

```bash

253

markdown2 [options] [files...]

254

255

Options:

256

--version Show version and exit

257

-v, --verbose More verbose output

258

--encoding ENCODING Specify encoding of text content (default: utf-8)

259

--html4tags Use HTML 4 style for empty element tags

260

-s MODE, --safe MODE Sanitize literal HTML ('escape' or 'replace')

261

-x EXTRA, --extras EXTRA

262

Turn on specific extras (can be used multiple times)

263

--use-file-vars Look for Emacs-style file variables to enable extras

264

--link-patterns-file FILE

265

Path to a link patterns file

266

--output FILE Output to file instead of stdout

267

--self-test Run internal self-tests

268

--compare Run against Markdown.pl for testing

269

```

270

271

**Examples with Extras:**

272

273

```bash

274

# Enable multiple extras

275

markdown2 -x fenced-code-blocks -x tables -x footnotes document.md

276

277

# With output file

278

markdown2 --extras fenced-code-blocks --extras tables document.md --output doc.html

279

280

# Safe mode with HTML escaping

281

markdown2 --safe escape document.md

282

283

# Custom encoding

284

markdown2 --encoding latin-1 document.md

285

```