CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-python-creole

A pure Python markup converter supporting creole2html, html2creole, html2ReSt, and html2textile conversions

Pending
Overview
Eval results
Files

macros-extensions.mddocs/

Macros and Extensions

Built-in macros for extended functionality and utilities for creating custom macros. python-creole supports macro expansion within Creole markup, enabling syntax highlighting, raw HTML inclusion, and custom processing functions.

Capabilities

Built-in Macros

Pre-defined macro functions for common extended markup needs.

def html(text: str) -> str: ...
def pre(text: str) -> str: ...  
def code(ext: str, text: str) -> str: ...

Usage Examples:

from creole.shared.example_macros import html, pre, code
from creole import creole2html

# HTML pass-through macro
macros = {'html': html}
markup = '<<html>><div class="custom">Custom HTML</div><</html>>'
result = creole2html(markup, macros=macros)
# Returns: '<div class="custom">Custom HTML</div>'

# Preformatted text macro
macros = {'pre': pre}
markup = '<<pre>>Code with    spaces\nand newlines<</pre>>'
result = creole2html(markup, macros=macros)
# Returns: '<pre>Code with    spaces\nand newlines</pre>'

# Syntax highlighting macro (requires pygments)
macros = {'code': code}
markup = '''<<code ext="python">>
def hello():
    print("Hello, world!")
<</code>>'''
result = creole2html(markup, macros=macros)
# Returns syntax-highlighted HTML if pygments is available

HTML Pass-through Macro

Allow raw HTML content within Creole markup.

def html(text: str) -> str

Parameters:

  • text: Raw HTML content to pass through unchanged

Returns: HTML string (unchanged input)

Usage Examples:

from creole.shared.example_macros import html

# Direct usage
output = html('<div class="highlight">Special content</div>')
# Returns: '<div class="highlight">Special content</div>'

# In Creole markup
creole_markup = '''
Normal paragraph.

<<html>>
<div class="custom-widget">
  <p>Custom HTML widget</p>
  <button onclick="alert('Hi!')">Click me</button>
</div>
<</html>>

Another paragraph.
'''

Preformatted Text Macro

Wrap text in HTML pre tags with proper escaping.

def pre(text: str) -> str

Parameters:

  • text: Text content to wrap in pre tags

Returns: HTML pre element with escaped content

Usage Examples:

from creole.shared.example_macros import pre

# Direct usage
output = pre('Code with <special> characters & symbols')
# Returns: '<pre>Code with &lt;special&gt; characters &amp; symbols</pre>'

# In Creole markup
creole_markup = '''
Here's some code:

<<pre>>
function example() {
    return "Hello <world>";
}
<</pre>>
'''

Syntax Highlighting Macro

Syntax highlight code using Pygments if available, otherwise fall back to preformatted text.

def code(ext: str, text: str) -> str

Parameters:

  • ext: File extension or language identifier (e.g., "python", ".py", "js", ".css")
  • text: Source code to highlight

Returns: HTML with syntax highlighting or preformatted text fallback

Usage Examples:

from creole.shared.example_macros import code

# Direct usage
python_code = '''
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)
'''
output = code("python", python_code)
# Returns syntax-highlighted HTML if pygments available

# Different language identifiers
js_output = code("js", "console.log('Hello world!');")
css_output = code(".css", "body { margin: 0; }")
generic_output = code("text", "Plain text content")

# In Creole markup
creole_markup = '''
Python example:

<<code ext="python">>
import sys
print(f"Python version: {sys.version}")
<</code>>

JavaScript example:

<<code ext=".js">>
const message = "Hello, world!";
document.body.innerHTML = message;
<</code>>
'''

Utility Functions

Pygments Integration

Helper functions for syntax highlighting integration.

def get_pygments_lexer(source_type: str, code: str): ...
def get_pygments_formatter(): ...

Usage Examples:

from creole.shared.utils import get_pygments_lexer, get_pygments_formatter

# Get lexer for specific language
lexer = get_pygments_lexer("python", "print('hello')")
formatter = get_pygments_formatter()

# Check if pygments is available
try:
    from pygments import highlight
    highlighted = highlight(code, lexer, formatter)
except ImportError:
    highlighted = f"<pre>{code}</pre>"  # Fallback

String Processing Utilities

Utilities for macro parameter processing.

def string2dict(raw_content: str) -> dict: ...
def dict2string(d: dict) -> str: ...

Usage Examples:

from creole.shared.utils import string2dict, dict2string

# Parse macro parameters
params = string2dict('key1="value1" key2=42 key3=true')
# Returns: {'key1': 'value1', 'key2': 42, 'key3': True}

# Convert back to string
param_string = dict2string({'lang': 'python', 'line_numbers': True})
# Returns: 'lang="python" line_numbers=True'

Creating Custom Macros

Simple Macro Functions

Macros are Python functions that take text input and return HTML output.

# Simple macro that wraps text in a div
def highlight_macro(text):
    return f'<div class="highlight">{text}</div>'

# Macro with parameters using string2dict
def box_macro(params, text):
    from creole.shared.utils import string2dict
    options = string2dict(params)
    css_class = options.get('class', 'box')
    color = options.get('color', 'blue')
    return f'<div class="{css_class}" style="border-color: {color};">{text}</div>'

# Usage in creole2html
macros = {
    'highlight': highlight_macro,
    'box': box_macro
}

markup = '''
<<highlight>>Important text<</highlight>>

<<box class="info" color="green">>
This is an info box.
<</box>>
'''

html = creole2html(markup, macros=macros)

Advanced Macro Patterns

# Macro with file inclusion
def include_macro(filename):
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            content = f.read()
        return f'<pre><code>{content}</code></pre>'
    except FileNotFoundError:
        return f'<p class="error">File not found: {filename}</p>'

# Macro with markdown processing
def markdown_macro(text):
    try:
        import markdown
        return markdown.markdown(text)
    except ImportError:
        return f'<pre>{text}</pre>'  # Fallback

# Conditional macro
def platform_macro(platform, text):
    import sys
    if sys.platform.startswith(platform):
        return text
    return ''  # Hide content on other platforms

macros = {
    'include': include_macro,
    'markdown': markdown_macro,
    'platform': platform_macro
}

Macro Error Handling

Macros should handle errors gracefully and provide fallback behavior:

def safe_macro(text):
    try:
        # Risky operation
        result = complex_processing(text)
        return result
    except Exception as e:
        # Log error and provide fallback
        import sys
        print(f"Macro error: {e}", file=sys.stderr)
        return f'<pre>{text}</pre>'  # Safe fallback

Testing Macros

from creole import creole2html

def test_macro():
    def test_macro_func(text):
        return f'<span class="test">{text}</span>'
    
    macros = {'test': test_macro_func}
    result = creole2html('<<test>>content<</test>>', macros=macros)
    expected = '<span class="test">content</span>'
    assert expected in result

test_macro()

Install with Tessl CLI

npx tessl i tessl/pypi-python-creole

docs

cli.md

core-conversions.md

index.md

macros-extensions.md

parsers-emitters.md

rest-tools.md

setup-utilities.md

tile.json