0
# Command Line Interface
1
2
Command-line tools for converting markdown files to HTML with batch processing and interactive modes. Provides a simple interface for markdown processing without requiring Python programming.
3
4
## Capabilities
5
6
### Main CLI Function
7
8
Primary entry point for command-line usage.
9
10
```python { .api }
11
def main(args: list[str] = None) -> int:
12
"""
13
Main CLI entry point.
14
15
Parameters:
16
- args: command line arguments (default: sys.argv[1:])
17
18
Returns:
19
- int: exit code (0 for success)
20
"""
21
```
22
23
### File Conversion
24
25
Convert markdown files to HTML output.
26
27
```python { .api }
28
def convert(filenames: list[str]) -> None:
29
"""
30
Convert multiple markdown files to HTML.
31
32
Parameters:
33
- filenames: list of markdown file paths to convert
34
"""
35
36
def convert_file(filename: str) -> None:
37
"""
38
Parse single markdown file and output HTML to stdout.
39
40
Parameters:
41
- filename: path to markdown file
42
43
Raises:
44
- SystemExit: on file read errors
45
"""
46
```
47
48
### Interactive Mode
49
50
Interactive markdown processing mode.
51
52
```python { .api }
53
def interactive() -> None:
54
"""
55
Interactive markdown parsing mode.
56
Parse user input and output HTML in REPL style.
57
"""
58
```
59
60
## Command Line Usage
61
62
### Basic Syntax
63
64
```bash
65
markdown-it [OPTIONS] [FILES...]
66
```
67
68
### Command Options
69
70
```bash
71
usage: markdown-it [-h] [-v] [filenames [filenames ...]]
72
73
Parse one or more markdown files, convert each to HTML, and print to stdout
74
75
positional arguments:
76
filenames specify an optional list of files to convert
77
78
optional arguments:
79
-h, --help show this help message and exit
80
-v, --version show program's version number and exit
81
```
82
83
### Batch Processing
84
85
Convert one or more files to HTML:
86
87
```bash
88
# Convert single file
89
markdown-it README.md
90
91
# Convert multiple files
92
markdown-it file1.md file2.md file3.md
93
94
# Redirect output to file
95
markdown-it input.md > output.html
96
97
# Process all markdown files in directory
98
markdown-it *.md > combined.html
99
```
100
101
**Example:**
102
103
```bash
104
$ echo "# Hello World\n\nThis is **bold** text." > hello.md
105
$ markdown-it hello.md
106
<h1>Hello World</h1>
107
<p>This is <strong>bold</strong> text.</p>
108
```
109
110
### Interactive Mode
111
112
Start interactive processing when no files are specified:
113
114
```bash
115
# Start interactive mode
116
markdown-it
117
118
# Interactive session example:
119
markdown-it-py [version 4.0.0] (interactive)
120
Type Ctrl-D to complete input, or Ctrl-C to exit.
121
>>> # Example
122
... > markdown *input*
123
...
124
<h1>Example</h1>
125
<blockquote>
126
<p>markdown <em>input</em></p>
127
</blockquote>
128
>>>
129
```
130
131
**Interactive Usage:**
132
133
```bash
134
$ markdown-it
135
markdown-it-py [version 4.0.0] (interactive)
136
Type Ctrl-D to complete input, or Ctrl-C to exit.
137
>>> **Bold text** and *italic text*
138
...
139
<p><strong>Bold text</strong> and <em>italic text</em></p>
140
141
>>> ## Heading
142
...
143
... - List item 1
144
... - List item 2
145
...
146
<h2>Heading</h2>
147
<ul>
148
<li>List item 1</li>
149
<li>List item 2</li>
150
</ul>
151
```
152
153
## Implementation Details
154
155
### Parser Configuration
156
157
The CLI uses default MarkdownIt configuration:
158
159
```python
160
# Equivalent Python usage
161
from markdown_it import MarkdownIt
162
163
md = MarkdownIt() # Uses 'commonmark' preset by default
164
html = md.render(markdown_content)
165
```
166
167
### Error Handling
168
169
The CLI handles common errors gracefully:
170
171
```python
172
# File not found
173
$ markdown-it nonexistent.md
174
Cannot open file "nonexistent.md".
175
# Exits with code 1
176
177
# Permission denied
178
$ markdown-it /root/restricted.md
179
Cannot open file "/root/restricted.md".
180
# Exits with code 1
181
```
182
183
### Character Encoding
184
185
Files are read with UTF-8 encoding and error handling:
186
187
```python
188
# Implementation detail
189
with open(filename, encoding="utf8", errors="ignore") as fin:
190
content = fin.read()
191
```
192
193
## Integration Examples
194
195
### Shell Scripts
196
197
Using markdown-it in shell scripts:
198
199
```bash
200
#!/bin/bash
201
# convert-docs.sh - Convert all markdown docs to HTML
202
203
for md_file in docs/*.md; do
204
html_file="${md_file%.md}.html"
205
echo "Converting $md_file -> $html_file"
206
markdown-it "$md_file" > "$html_file"
207
done
208
209
echo "Conversion complete!"
210
```
211
212
### Makefile Integration
213
214
Using markdown-it in build systems:
215
216
```makefile
217
# Makefile
218
MARKDOWN_FILES := $(wildcard *.md)
219
HTML_FILES := $(MARKDOWN_FILES:.md=.html)
220
221
.PHONY: all clean
222
223
all: $(HTML_FILES)
224
225
%.html: %.md
226
markdown-it $< > $@
227
228
clean:
229
rm -f $(HTML_FILES)
230
231
# Usage: make all
232
```
233
234
### CI/CD Pipeline
235
236
Using in continuous integration:
237
238
```yaml
239
# .github/workflows/docs.yml
240
name: Generate Documentation
241
242
on: [push, pull_request]
243
244
jobs:
245
generate-docs:
246
runs-on: ubuntu-latest
247
steps:
248
- uses: actions/checkout@v2
249
250
- name: Setup Python
251
uses: actions/setup-python@v2
252
with:
253
python-version: '3.10'
254
255
- name: Install markdown-it-py
256
run: pip install markdown-it-py
257
258
- name: Convert README to HTML
259
run: |
260
markdown-it README.md > docs/index.html
261
markdown-it CHANGELOG.md > docs/changelog.html
262
263
- name: Deploy to GitHub Pages
264
uses: peaceiris/actions-gh-pages@v3
265
with:
266
github_token: ${{ secrets.GITHUB_TOKEN }}
267
publish_dir: ./docs
268
```
269
270
### Docker Integration
271
272
Using in containerized environments:
273
274
```dockerfile
275
# Dockerfile
276
FROM python:3.10-slim
277
278
RUN pip install markdown-it-py
279
280
WORKDIR /app
281
COPY . .
282
283
# Convert all markdown files
284
RUN find . -name "*.md" -exec markdown-it {} \; > combined.html
285
286
# Or use as entry point
287
ENTRYPOINT ["markdown-it"]
288
```
289
290
```bash
291
# Build and run
292
docker build -t markdown-converter .
293
294
# Convert files
295
docker run --rm -v $(pwd):/app markdown-converter README.md
296
297
# Interactive mode
298
docker run --rm -it markdown-converter
299
```
300
301
## Programmatic CLI Usage
302
303
### Calling from Python
304
305
Invoke CLI functionality programmatically:
306
307
```python
308
from markdown_it.cli.parse import main, convert_file, interactive
309
import sys
310
311
# Call main function directly
312
exit_code = main(['--help'])
313
314
# Convert specific file
315
try:
316
convert_file('README.md')
317
except SystemExit as e:
318
print(f"Conversion failed: {e}")
319
320
# Programmatic file conversion (safer approach)
321
from markdown_it import MarkdownIt
322
import sys
323
324
def safe_convert_file(filename):
325
"""Convert file with proper error handling."""
326
try:
327
with open(filename, 'r', encoding='utf-8') as f:
328
content = f.read()
329
330
md = MarkdownIt()
331
html = md.render(content)
332
return html
333
334
except FileNotFoundError:
335
print(f"Error: File '{filename}' not found")
336
return None
337
except PermissionError:
338
print(f"Error: Permission denied reading '{filename}'")
339
return None
340
341
# Usage
342
html_output = safe_convert_file('example.md')
343
if html_output:
344
print(html_output)
345
```
346
347
### Subprocess Integration
348
349
Call CLI from other programs:
350
351
```python
352
import subprocess
353
import tempfile
354
355
def convert_markdown_string(markdown_text):
356
"""Convert markdown string using CLI."""
357
with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False) as f:
358
f.write(markdown_text)
359
temp_file = f.name
360
361
try:
362
result = subprocess.run(
363
['markdown-it', temp_file],
364
capture_output=True,
365
text=True,
366
check=True
367
)
368
return result.stdout
369
370
except subprocess.CalledProcessError as e:
371
print(f"Conversion failed: {e}")
372
return None
373
374
finally:
375
import os
376
os.unlink(temp_file)
377
378
# Usage
379
html = convert_markdown_string("# Hello\n\n**World**")
380
print(html)
381
```