Skip to main content

Markdown rendering for CLI applications with syntax highlighting

Project description

clickmd

PyPI version Python 3.10+ License: Apache-2.0 Tests codecov

Markdown rendering for CLI applications with syntax highlighting.

clickmd provides beautiful terminal output with:

  • ๐ŸŽจ Syntax highlighting for code blocks (Python, TypeScript, JSON, YAML, Bash, etc.)
  • ๐Ÿ“ Markdown rendering with headers, bold, links, and more
  • ๐Ÿ”ง Zero dependencies for core functionality
  • ๐Ÿ–ฑ๏ธ Optional Click integration for CLI decorators

Installation

# Core package (no dependencies)
pip install clickmd

# With Click support
pip install clickmd[click]

Quick Start

Basic Usage (No Dependencies)

from clickmd import md, echo

# Render markdown with syntax highlighting
md("""
# Hello World

This is **bold** and this is a [link](https://example.com).

```python
def greet(name: str) -> str:
    return f"Hello, {name}!"

""")

Smart echo - auto-detects markdown

echo("## Status Update") echo("Regular text without markdown")


### With Click Integration

```python
import clickmd as click

@click.group()
def cli():
    """My awesome CLI tool"""
    pass

@cli.command()
@click.option("--name", "-n", default="World")
def hello(name: str):
    """Say hello"""
    click.md(f"""
## ๐Ÿ‘‹ Hello, {name}!

Welcome to **clickmd** - making CLIs beautiful.
    """)

if __name__ == "__main__":
    cli()

Features

Syntax Highlighting

clickmd provides syntax highlighting for multiple languages:

Language Extensions Highlight Features
Python .py Keywords, strings, comments, decorators
TypeScript/JavaScript .ts, .js Keywords, strings, template literals
JSON .json Keys, strings, numbers, booleans
YAML .yaml, .yml Keys, values, comments
Bash/Shell .sh, .bash Commands, comments
Markdown .md Headers, bold, links
Log .log Errors (red), warnings (yellow), success (green)

Markdown Elements

from clickmd import md

md("""
# Heading 1
## Heading 2
### Heading 3

**Bold text** and regular text.

[Links](https://example.com) are supported.

```python
# Code blocks with syntax highlighting
print("Hello, World!")
  • List items
  • Are rendered
  • Correctly """)

### MarkdownRenderer Class

For more control, use the `MarkdownRenderer` class directly:

```python
from clickmd import MarkdownRenderer
import sys

renderer = MarkdownRenderer(use_colors=True, stream=sys.stdout)
renderer.heading(1, "My Title")
renderer.codeblock("python", 'print("Hello!")')

Progress and Status Output

from clickmd import md

# Log-style output with automatic coloring
md("""
```log
๐Ÿš€ Starting process...
๐Ÿ“ฆ Installing dependencies...
โœ… Build successful!
โš ๏ธ Warning: deprecated API
๐Ÿ›‘ Error: connection failed

""")


## API Reference

### Core Functions

#### `md(text: str) -> None`
Render markdown text with syntax highlighting.

#### `echo(message, file=None, nl=True, err=False, color=None) -> None`
Smart echo that auto-detects markdown and renders it.

#### `render_markdown(text, text_lang="markdown", stream=None, use_colors=True) -> None`
Low-level markdown rendering function.

#### `get_renderer(stream=None, use_colors=True) -> MarkdownRenderer`
Get a `MarkdownRenderer` instance.

### Click Decorators (requires `click` package)

When `click` is installed, these decorators are available:

- `@clickmd.group()` - Create a command group
- `@clickmd.command()` - Create a command
- `@clickmd.option()` - Add an option
- `@clickmd.argument()` - Add an argument
- `@clickmd.pass_context` - Pass Click context
- `clickmd.Choice` - Choice type
- `clickmd.Path` - Path type

### Constants

- `CLICK_AVAILABLE: bool` - Whether Click is installed

## Additional Features

### Interactive Menus

```python
import clickmd

choice = clickmd.menu("## Choose Provider", [
    ("groq", "Groq โ€” fast & free tier"),
    ("openrouter", "OpenRouter โ€” multi-model"),
    ("ollama", "Ollama โ€” local, no API key"),
])

Tables & Panels

from clickmd import table, panel

table(
    headers=["Name", "Version", "Status"],
    rows=[
        ["clickmd", "1.1.0", "โœ… OK"],
        ["click", "8.1.7", "โœ… OK"],
    ],
)

panel("Deployment complete!", title="Success", style="green")

Logger

from clickmd import get_logger

log = get_logger("myapp")
log.info("Starting process...")
log.success("Build complete!")
log.warning("Deprecated API")
log.error("Connection failed")

Themes

from clickmd import set_theme, list_themes

list_themes()            # Show available themes
set_theme("monokai")     # Switch theme

Developer Tools

from clickmd import debug, inspect_obj, diff, tree

debug(my_variable)                    # Pretty-print with type info
inspect_obj(my_object)                # Show object attributes
diff("old text", "new text")          # Side-by-side diff
tree("/path/to/dir")                  # Directory tree

Examples

See the examples/ directory for 17 demo scripts:

  • basic.py โ€” Basic markdown rendering
  • cli_app.py โ€” Full CLI application with Click
  • custom_renderer.py โ€” Custom renderer configuration
  • colored_logging.py โ€” Log-style colored output
  • phase1_features.py โ€” Tables, panels, blockquotes, checklists
  • phase3_progress.py โ€” Progress bars, spinners, live updates
  • phase4_themes.py โ€” Theming system
  • phase5_devtools.py โ€” Debug, inspect, diff, tree tools
  • logger_usage.py โ€” Structured logging
  • markdown_help.py โ€” Markdown help formatter for Click

Project Structure

clickmd/
โ”œโ”€โ”€ src/clickmd/          # Package source (src layout)
โ”‚   โ”œโ”€โ”€ __init__.py       # Public API: md(), echo(), menu(), select()
โ”‚   โ”œโ”€โ”€ renderer.py       # Core markdown renderer & syntax highlighting
โ”‚   โ”œโ”€โ”€ decorators.py     # Click decorator re-exports
โ”‚   โ”œโ”€โ”€ help.py           # Markdown help formatter for Click
โ”‚   โ”œโ”€โ”€ logger.py         # Markdown-aware structured logger
โ”‚   โ”œโ”€โ”€ progress.py       # Progress bars, spinners, live updates
โ”‚   โ”œโ”€โ”€ themes.py         # Color themes & NO_COLOR support
โ”‚   โ”œโ”€โ”€ devtools.py       # Debug, inspect, diff, tree tools
โ”‚   โ”œโ”€โ”€ rich_backend.py   # Optional Rich integration
โ”‚   โ””โ”€โ”€ py.typed          # PEP 561 type marker
โ”œโ”€โ”€ tests/                # Test suite (69 tests)
โ”œโ”€โ”€ examples/             # 17 demo scripts
โ”œโ”€โ”€ docs/                 # API reference & contributing guide
โ”œโ”€โ”€ scripts/              # Build & version tools
โ”œโ”€โ”€ tools/                # Markdown-to-HTML converter
โ”œโ”€โ”€ pyproject.toml        # Project config (hatchling)
โ””โ”€โ”€ Makefile              # Dev commands

Development

# Clone the repository
git clone https://github.com/wronai/clickmd.git
cd clickmd

# Install development dependencies
pip install -e ".[dev,click]"

# Run tests
make test

# Run linter & format
make lint
make format

# Build & publish
make build
make publish

License

Licensed under Apache-2.0.

Apache License 2.0 - see LICENSE for details.

Author

Tom Sapletta

Created by Tom Sapletta - tom@sapletta.com

Contributing

Contributions are welcome! Please read our Contributing Guide first.

Related Projects

  • Click - Python CLI framework
  • Rich - Rich text and beautiful formatting

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

clickmd-1.1.9.tar.gz (39.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

clickmd-1.1.9-py3-none-any.whl (43.7 kB view details)

Uploaded Python 3

File details

Details for the file clickmd-1.1.9.tar.gz.

File metadata

  • Download URL: clickmd-1.1.9.tar.gz
  • Upload date:
  • Size: 39.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for clickmd-1.1.9.tar.gz
Algorithm Hash digest
SHA256 07cf361d5beff26918096112bf708c03c063eef2f30791637a2310f89faef05c
MD5 63ab7217ed39ee0b5425de4c26bde8a7
BLAKE2b-256 2be96dc18afc04973d14d1b20ee590dfe525bbf865f5912e66290988ddac2336

See more details on using hashes here.

File details

Details for the file clickmd-1.1.9-py3-none-any.whl.

File metadata

  • Download URL: clickmd-1.1.9-py3-none-any.whl
  • Upload date:
  • Size: 43.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for clickmd-1.1.9-py3-none-any.whl
Algorithm Hash digest
SHA256 4924fa4b627dad4880a2011cdbe87739ce03b433ff9a9b813d7e37f18b739332
MD5 c882f98ae59f84772e83d692be271df6
BLAKE2b-256 04bb9f7553ad5dfc306365aaa06c28bc868eb353eaec5197c5a8b8e861fad249

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page