CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-markdown2

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

Pending
Overview
Eval results
Files

code-syntax-extras.mddocs/

Code and Syntax Extras

Extensions for enhanced code block processing, syntax highlighting, and developer-friendly features that improve the handling of code content in markdown documents.

Capabilities

Fenced Code Blocks

GitHub-style fenced code blocks with optional syntax highlighting and language specification.

# fenced-code-blocks extra - enables ``` style code blocks
extras = ["fenced-code-blocks"]

# highlightjs-lang extra - language specification for highlight.js
extras = ["fenced-code-blocks", "highlightjs-lang"]

Usage Examples:

import markdown2

# Basic fenced code blocks
markdown_text = '''
```python
def hello_world():
    print("Hello, World!")
function helloWorld() {
    console.log("Hello, World!");
}

'''

html = markdown2.markdown(markdown_text, extras=["fenced-code-blocks"])

With highlight.js language specification

html = markdown2.markdown( markdown_text, extras=["fenced-code-blocks", "highlightjs-lang"] )

Adds appropriate class attributes for highlight.js

**Fenced Code Block Features:**
- Supports language specification: ````python`, ```javascript`, etc.
- No indentation required (unlike standard markdown code blocks)
- Preserves whitespace and formatting
- Can include metadata and options
- Compatible with syntax highlighters like Pygments and highlight.js

### Python Shell Integration

Special processing for Python interactive shell sessions.

```python { .api }
# pyshell extra - treats unindented Python interactive sessions as code blocks
extras = ["pyshell"]

Usage Examples:

import markdown2

shell_text = '''
>>> import math
>>> math.pi
3.141592653589793
>>> math.sqrt(16)
4.0
>>> for i in range(3):
...     print(f"Number: {i}")
... 
Number: 0
Number: 1
Number: 2
'''

html = markdown2.markdown(shell_text, extras=["pyshell"])
# Automatically detects and formats Python shell sessions

Syntax Highlighting Integration

Integration with external syntax highlighting libraries.

# code-color extra (used in MarkdownWithExtras) - enables Pygments syntax highlighting
extras = ["fenced-code-blocks", "code-color"]

# For highlight.js integration
extras = ["fenced-code-blocks", "highlightjs-lang"]

Usage Examples:

import markdown2

code_text = '''
```python
import requests
from typing import Dict, List

def fetch_data(url: str) -> Dict:
    """Fetch JSON data from URL."""
    response = requests.get(url)
    response.raise_for_status()
    return response.json()

class DataProcessor:
    def __init__(self, data: List[Dict]):
        self.data = data
    
    def process(self) -> List[str]:
        return [item['name'] for item in self.data]

'''

With Pygments syntax highlighting (requires pygments package)

html = markdown2.markdown( code_text, extras=["fenced-code-blocks", "code-color"] )

With highlight.js classes

html = markdown2.markdown( code_text, extras=["fenced-code-blocks", "highlightjs-lang"] )

## Configuration and Options

### Fenced Code Block Options

Fenced code blocks support various language specifiers and options:

```markdown
```python
# Basic Python code block
def example():
    pass
# With filename metadata
def example():
    pass
# With CSS classes
def example():
    pass
### Language Support

Common language identifiers supported:
- **Python**: `python`, `py`
- **JavaScript**: `javascript`, `js`
- **TypeScript**: `typescript`, `ts`
- **HTML**: `html`, `htm`
- **CSS**: `css`
- **SQL**: `sql`
- **Shell/Bash**: `bash`, `sh`, `shell`
- **JSON**: `json`
- **XML**: `xml`
- **Many more depending on syntax highlighter

### Pygments Integration

When using the `code-color` extra with Pygments installed:

```python
import markdown2

# Requires: pip install pygments
html = markdown2.markdown(
    code_with_language_blocks,
    extras=["fenced-code-blocks", "code-color"]
)
# Generates full HTML with CSS classes for syntax highlighting

Highlight.js Integration

When using highlightjs-lang extra:

import markdown2

html = markdown2.markdown(
    code_text,
    extras=["fenced-code-blocks", "highlightjs-lang"]
)
# Generates <code class="language-python"> for highlight.js to process

Advanced Code Processing

Code-Friendly Text Processing

Combine code extras with text processing for better code documentation:

import markdown2

documentation = '''
# API Documentation

The `user_manager.create_user()` function creates a new user:

```python
from user_manager import create_user

user = create_user(
    username="john_doe",
    email="john@example.com",
    full_name="John Doe"
)

Note: The function_name_with_underscores won't be emphasized. '''

html = markdown2.markdown( documentation, extras=[ "fenced-code-blocks", "code-color", # Syntax highlighting "code-friendly", # Don't emphasize underscores "header-ids" # For documentation navigation ] )

### Python Shell Documentation

Document interactive Python sessions:

```python
import markdown2

tutorial_text = '''
# Python Tutorial

Let's explore some basic Python operations:

>>> name = "World"
>>> message = f"Hello, {name}!"
>>> print(message)
Hello, World!
>>> 
>>> numbers = [1, 2, 3, 4, 5]
>>> squared = [n**2 for n in numbers]
>>> print(squared)
[1, 4, 9, 16, 25]

The `pyshell` extra automatically formats these interactive sessions.
'''

html = markdown2.markdown(
    tutorial_text,
    extras=["pyshell", "code-friendly", "fenced-code-blocks"]
)

Integration Examples

Complete Development Documentation Setup

import markdown2

# Comprehensive setup for code documentation
extras = [
    "fenced-code-blocks",    # GitHub-style code blocks
    "code-color",           # Syntax highlighting with Pygments
    "code-friendly",        # Don't emphasize underscores in code
    "pyshell",             # Format Python shell sessions
    "tables",              # For API reference tables
    "header-ids",          # For navigation
    "toc"                  # Table of contents
]

processor = markdown2.Markdown(extras=extras)

# Process documentation files
api_docs = processor.convert(api_markdown)
tutorial = processor.convert(tutorial_markdown)
examples = processor.convert(examples_markdown)

Web Development Integration

import markdown2

# For web applications with client-side highlighting
web_extras = [
    "fenced-code-blocks",
    "highlightjs-lang",     # Use highlight.js classes
    "tables",
    "header-ids"
]

html = markdown2.markdown(content, extras=web_extras)
# Include highlight.js in your web page to process the code blocks

Install with Tessl CLI

npx tessl i tessl/pypi-markdown2

docs

code-syntax-extras.md

core-conversion.md

index.md

link-reference-extras.md

processor-classes.md

special-content-extras.md

structure-layout-extras.md

text-processing-extras.md

tile.json