Markdown Test 2: Code Blocks and Syntax Highlighting

December 02, 2023Test Author2403 words13 min read

Markdown Test 2: Code Blocks and Syntax Highlighting

This test focuses on code blocks, syntax highlighting across various programming languages, and technical content formatting. We’ll test edge cases, special characters, and ensure our syntax highlighter handles everything gracefully.

Inline Code Variations

Inline code can appear in many contexts:

  • Simple inline code: const x = 42
  • Multiple inline codes in one line: let, const, and var are JavaScript keywords
  • Code with operators: x += 1, y *= 2, z !== false
  • File paths: /usr/local/bin, C:\Windows\System32, ~/Documents/code.rs
  • Commands: npm install, cargo build --release, git push origin main
  • URLs in code: https://api.example.com/v1/posts

Special characters in inline code: <div>, &amp;, "quotes", 'apostrophes', ${}, `backticks`

Basic Code Blocks

Without Language Specification

This is a simple code block without syntax highlighting.
It preserves    spacing    and line breaks.
Special characters: < > & " ' ` $ { } [ ] ( ) 
Unicode: → ← ↑ ↓ λ ∑ ∏ ≠ ≤ ≥

With Language but No Highlighting

Plain text block with language specified as 'text'.
This won't have syntax highlighting but maintains formatting.
Useful for configuration files, logs, or output examples.

Programming Languages Showcase

Rust - Systems Programming

// Fast Fibonacci using matrix exponentiation and the golden ratio
use std::ops::Mul;

#[derive(Clone, Copy, Debug)]
struct Matrix2x2 {
    a: f64, b: f64,
    c: f64, d: f64,
}

impl Mul for Matrix2x2 {
    type Output = Self;
    
    fn mul(self, rhs: Self) -> Self {
        Matrix2x2 {
            a: self.a * rhs.a + self.b * rhs.c,
            b: self.a * rhs.b + self.b * rhs.d,
            c: self.c * rhs.a + self.d * rhs.c,
            d: self.c * rhs.b + self.d * rhs.d,
        }
    }
}

fn matrix_pow(m: Matrix2x2, n: u32) -> Matrix2x2 {
    if n == 0 {
        Matrix2x2 { a: 1.0, b: 0.0, c: 0.0, d: 1.0 } // Identity
    } else if n == 1 {
        m
    } else if n % 2 == 0 {
        let half = matrix_pow(m, n / 2);
        half * half
    } else {
        m * matrix_pow(m, n - 1)
    }
}

fn fibonacci_matrix(n: u32) -> u64 {
    let fib_matrix = Matrix2x2 { a: 1.0, b: 1.0, c: 1.0, d: 0.0 };
    let result = matrix_pow(fib_matrix, n);
    result.b as u64
}

// Using Binet's formula with the golden ratio
fn fibonacci_golden(n: u32) -> u64 {
    let phi = (1.0 + 5.0_f64.sqrt()) / 2.0; // Golden ratio
    let psi = (1.0 - 5.0_f64.sqrt()) / 2.0;
    ((phi.powi(n as i32) - psi.powi(n as i32)) / 5.0_f64.sqrt()).round() as u64
}

fn main() {
    println!("Fibonacci via Matrix Exponentiation vs Golden Ratio:");
    for n in [10, 20, 30, 40, 50] {
        let matrix = fibonacci_matrix(n);
        let golden = fibonacci_golden(n);
        println!("F({n:2}) = {matrix:12} (matrix) | {golden:12} (golden ratio)");
    }
    
    // Compute large Fibonacci numbers
    // Note: Golden ratio method loses precision for large n due to floating-point arithmetic
    println!("\nF(92) = {} (largest that fits in u64)", fibonacci_matrix(92));
}

JavaScript/TypeScript - Modern Web Development

// Conway's Game of Life in TypeScript
type Grid = boolean[][];

class GameOfLife {
    private grid: Grid;
    private size: number;
    
    constructor(size: number, pattern?: [number, number][]) {
        this.size = size;
        this.grid = Array(size).fill(null)
            .map(() => Array(size).fill(false));
        
        // Initialize with pattern if provided
        pattern?.forEach(([x, y]) => {
            if (x >= 0 && x < size && y >= 0 && y < size) {
                this.grid[y][x] = true;
            }
        });
    }
    
    private countNeighbors(x: number, y: number): number {
        let count = 0;
        for (let dy = -1; dy <= 1; dy++) {
            for (let dx = -1; dx <= 1; dx++) {
                if (dx === 0 && dy === 0) continue;
                const nx = x + dx;
                const ny = y + dy;
                if (nx >= 0 && nx < this.size && 
                    ny >= 0 && ny < this.size && 
                    this.grid[ny][nx]) {
                    count++;
                }
            }
        }
        return count;
    }
    
    step(): void {
        const newGrid: Grid = this.grid.map(row => [...row]);
        
        for (let y = 0; y < this.size; y++) {
            for (let x = 0; x < this.size; x++) {
                const neighbors = this.countNeighbors(x, y);
                const alive = this.grid[y][x];
                
                // Conway's rules
                if (alive && (neighbors < 2 || neighbors > 3)) {
                    newGrid[y][x] = false; // Dies
                } else if (!alive && neighbors === 3) {
                    newGrid[y][x] = true; // Born
                }
            }
        }
        
        this.grid = newGrid;
    }
    
    display(): string {
        return this.grid
            .map(row => row.map(cell => cell ? '' : '·').join(' '))
            .join('\n');
    }
}

// Create a glider pattern
const glider: [number, number][] = [
    [1, 0], [2, 1], [0, 2], [1, 2], [2, 2]
];

const game = new GameOfLife(10, glider);
console.log("Generation 0:");
console.log(game.display());

for (let i = 1; i <= 5; i++) {
    game.step();
    console.log(`\nGeneration ${i}:`);
    console.log(game.display());
}

Python - Data Science & Scripting

# Mandelbrot set visualization using NumPy vectorization
import numpy as np
from typing import Tuple

def mandelbrot_set(
    width: int = 800, 
    height: int = 600,
    x_min: float = -2.5, 
    x_max: float = 1.0,
    y_min: float = -1.25, 
    y_max: float = 1.25,
    max_iter: int = 100
) -> np.ndarray:
    """Generate Mandelbrot set using vectorized operations."""
    
    # Create coordinate arrays
    x = np.linspace(x_min, x_max, width)
    y = np.linspace(y_min, y_max, height)
    X, Y = np.meshgrid(x, y)
    
    # Complex grid
    C = X + 1j * Y
    Z = np.zeros_like(C)
    M = np.zeros(C.shape, dtype=int)
    
    # Vectorized iteration
    for i in range(max_iter):
        # Only compute for points not yet escaped
        mask = np.abs(Z) <= 2
        Z[mask] = Z[mask]**2 + C[mask]
        M[mask] = i
    
    return M

def zoom_coordinates(center: complex, zoom: float) -> Tuple[float, float, float, float]:
    """Calculate viewport coordinates for a zoom level."""
    width = 3.5 / zoom
    height = 2.5 / zoom
    return (
        center.real - width/2, center.real + width/2,
        center.imag - height/2, center.imag + height/2
    )

# Generate and display interesting regions
interesting_points = [
    ("Main set", complex(-0.5, 0), 1),
    ("Elephant valley", complex(0.275, 0), 50),
    ("Seahorse valley", complex(-0.75, 0.1), 150),
    ("Triple spiral", complex(-0.088, 0.654), 300),
    ("Mini mandelbrot", complex(-1.25066, 0.02012), 5000),
]

# ASCII art visualization
def ascii_mandelbrot(data: np.ndarray) -> str:
    """Convert Mandelbrot data to ASCII art."""
    # Characters arranged roughly by visual density (approximate)
    chars = " .'`^\",:;Il!i><~+_-?][}{1)(|/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$"
    normalized = (data / data.max() * (len(chars) - 1)).astype(int)
    
    # Downsample for terminal display
    h, w = normalized.shape
    step = max(1, h // 40)
    downsampled = normalized[::step, ::step*2]  # 2x width for aspect ratio
    
    return '\n'.join(
        ''.join(chars[val] for val in row)
        for row in downsampled
    )

# Generate ASCII visualization
print("Mandelbrot Set - Main View")
data = mandelbrot_set(160, 120, max_iter=50)
print(ascii_mandelbrot(data))

# Calculate some interesting properties
def mandelbrot_area_monte_carlo(samples: int = 1000000) -> float:
    """Estimate area of Mandelbrot set using Monte Carlo."""
    # Random points in [-2, 0.5] x [-1.25, 1.25]
    x = np.random.uniform(-2, 0.5, samples)
    y = np.random.uniform(-1.25, 1.25, samples)
    c = x + 1j * y
    
    z = np.zeros_like(c)
    in_set = np.ones(samples, dtype=bool)
    
    for _ in range(100):
        z = z**2 + c
        in_set &= np.abs(z) <= 2
    
    # Area = sampled area × fraction in set
    return 2.5 * 2.5 * np.sum(in_set) / samples

print(f"\nEstimated Mandelbrot set area: {mandelbrot_area_monte_carlo():.4f}")

SQL - Database Queries

-- Recursive Common Table Expression: Finding cycles in a graph
-- and calculating PageRank-style importance scores

WITH RECURSIVE 
-- Define our graph edges (who follows whom)
followers AS (
    VALUES 
        ('Alice', 'Bob'), ('Bob', 'Charlie'), ('Charlie', 'Alice'),  -- Cycle!
        ('Alice', 'Diana'), ('Diana', 'Eve'), ('Eve', 'Frank'),
        ('Frank', 'Diana'), ('Bob', 'Eve'), ('Charlie', 'Frank')
),
-- Find all paths and detect cycles
paths AS (
    -- Base case: start from each person
    SELECT 
        follower AS start_node,
        followed AS current_node,
        ARRAY[follower, followed] AS path,
        false AS has_cycle,
        1 AS depth
    FROM followers
    
    UNION ALL
    
    -- Recursive case: extend paths
    SELECT 
        p.start_node,
        f.followed AS current_node,
        p.path || f.followed AS path,
        f.followed = ANY(p.path) AS has_cycle,  -- Cycle detection
        p.depth + 1
    FROM paths p
    JOIN followers f ON p.current_node = f.follower
    WHERE p.depth < 10  -- Prevent infinite recursion
        AND NOT p.has_cycle  -- Stop when cycle found
),
-- Calculate influence scores (similar to PageRank)
influence AS (
    SELECT 
        person,
        COUNT(DISTINCT follower) AS direct_followers,
        COUNT(DISTINCT path.start_node) AS reach,  -- Unique people who can reach them
        MAX(path.depth) AS max_influence_distance,
        ARRAY_AGG(DISTINCT path.start_node) FILTER (WHERE path.depth > 2) AS indirect_influence
    FROM (
        SELECT DISTINCT unnest(path) AS person FROM paths
    ) people
    LEFT JOIN followers ON people.person = followers.followed
    LEFT JOIN paths path ON people.person = path.current_node
    GROUP BY person
),
-- Find strongly connected components (cycles)
cycles AS (
    SELECT DISTINCT
        ARRAY_TO_STRING(
            ARRAY(SELECT unnest(path) ORDER BY unnest), 
            ''
        ) || '' || path[1] AS cycle_visualization,
        path
    FROM paths
    WHERE has_cycle 
        AND current_node = start_node  -- Complete cycle
)
-- Final results
SELECT 
    'Influence Ranking:' AS analysis_type,
    i.person AS entity,
    i.direct_followers AS metric1,
    i.reach AS metric2,
    ROUND(
        (i.direct_followers * 0.3 + i.reach * 0.7)::numeric, 
        2
    ) AS influence_score
FROM influence i
ORDER BY influence_score DESC

UNION ALL

SELECT 
    'Detected Cycles:' AS analysis_type,
    cycle_visualization AS entity,
    array_length(path, 1) - 1 AS metric1,  -- Cycle length
    NULL AS metric2,
    NULL AS influence_score
FROM cycles

UNION ALL

-- Graph statistics using window functions
SELECT DISTINCT
    'Graph Statistics:' AS analysis_type,
    'Total Nodes: ' || COUNT(DISTINCT person) OVER() AS entity,
    COUNT(DISTINCT start_node || '' || current_node) OVER() AS metric1,
    ROUND(AVG(depth) OVER()::numeric, 2) AS metric2,
    NULL AS influence_score
FROM paths, influence
LIMIT 1;

-- Bonus: Generate a Graphviz DOT representation
/*
SELECT 'digraph SocialNetwork {' 
UNION ALL
SELECT DISTINCT '    ' || follower || ' -> ' || followed || ';'
FROM followers
UNION ALL
SELECT '}';
*/

Shell Scripting - Bash

#!/usr/bin/env bash
# A self-modifying quine that tracks its own execution count

# Initialize execution counter if this is first run
if ! grep -q "^# Execution count:" "$0" 2>/dev/null; then
    echo "# Execution count: 0" >> "$0"
fi

# Read current count
count=$(grep "^# Execution count:" "$0" | awk '{print $4}')
((count++))

# Update count in the script itself
if [[ "$(uname)" == "Darwin" ]]; then
    # macOS sed requires -i ''
    sed -i '' "s/^# Execution count: .*$/# Execution count: $count/" "$0"
else
    # GNU sed
    sed -i "s/^# Execution count: .*$/# Execution count: $count/" "$0"
fi

# The quine part - print own source with decorations
echo "=== Quine Output (Run #$count) ==="
cat "$0" | while IFS= read -r line; do
    # Syntax highlighting simulation
    if [[ "$line" =~ ^#.*$ ]]; then
        printf "\033[32m%s\033[0m\n" "$line"  # Comments in green
    elif [[ "$line" =~ ^(if|then|else|fi|while|do|done) ]]; then
        printf "\033[34m%s\033[0m\n" "$line"  # Keywords in blue
    else
        echo "$line"
    fi
done

# Fractal pattern generator using pure bash
fractal() {
    local depth=$1 x=$2 y=$3 size=$4
    ((depth <= 0)) && return
    
    # Draw current level
    printf "\033[%d;%dH*" $((y)) $((x*2))
    
    # Recursive calls for fractal branches
    fractal $((depth-1)) $((x-size)) $((y-size/2)) $((size/2))
    fractal $((depth-1)) $((x+size)) $((y-size/2)) $((size/2))
    fractal $((depth-1)) $((x)) $((y+size)) $((size/2))
}

echo -e "\n\n=== Bash Fractal Tree ==="
# Clear area and draw fractal
for i in {1..20}; do printf "\033[%d;1H%-80s" $((i+25)) " "; done
fractal 5 40 30 8
printf "\033[50;1H"  # Move cursor to bottom

# One-liner magic: Generate prime numbers using bash
echo -e "\n=== First 20 Primes (bash one-liner) ==="
seq 2 100 | while read n; do 
    (($(factor $n | wc -w)==2)) && echo -n "$n "
done | head -20

echo -e "\n\n=== Process Tree Art ==="
# Visualize process tree as ASCII art
ps aux | awk 'NR>1{print $2,$3,$11}' | sort -k2 -nr | head -10 | \
while read pid cpu cmd; do
    width=$(echo "scale=0; $cpu * 50 / 100" | bc 2>/dev/null || echo 10)
    printf "%-6s [%3.1f%%] " "$pid" "$cpu"
    printf '█%.0s' $(seq 1 $width 2>/dev/null || seq 1 10)
    printf " %s\n" "${cmd:0:40}"
done

echo -e "\n=== Script Self-Analysis ==="
echo "Script size: $(wc -c < "$0") bytes"
echo "Line count: $(wc -l < "$0") lines"
echo "Word count: $(wc -w < "$0") words"
echo "Unique words: $(tr -cs '[:alnum:]' '\n' < "$0" | sort -u | wc -l)"

# The classic fork bomb (DON'T UNCOMMENT!)
# :(){ :|:& };:

# Execution count: will be added here

Edge Cases and Special Scenarios

Very Long Lines

# This is an extremely long line that should test how the syntax highlighter handles line wrapping, horizontal scrolling, and whether it maintains proper syntax highlighting across very long lines without breaking the layout or causing performance issues in the browser when rendering

Nested Language Blocks

Here’s HTML with embedded CSS and JavaScript:

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        /* CSS within HTML */
        .highlight {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 1rem;
            border-radius: 0.5rem;
            animation: pulse 2s ease-in-out infinite;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.7; }
        }
    </style>
</head>
<body>
    <div class="highlight">
        <h1>Nested Languages Demo</h1>
    </div>
    
    <script>
        // JavaScript within HTML
        document.addEventListener('DOMContentLoaded', () => {
            const msg = `Current time: ${new Date().toLocaleTimeString()}`;
            console.log(msg);
            
            // Dynamic style injection
            const style = document.createElement('style');
            style.textContent = `
                body::after {
                    content: '${msg}';
                    position: fixed;
                    bottom: 10px;
                    right: 10px;
                    background: rgba(0,0,0,0.8);
                    color: white;
                    padding: 5px 10px;
                    border-radius: 3px;
                }
            `;
            document.head.appendChild(style);
        });
    </script>
</body>
</html>

Unicode in Code

# Unicode variable names and strings
def calculate_Σ(numbers):
    """Calculate sum (Σ) of numbers."""
    π = 3.14159
    φ = 1.618
    return sum(numbers) * π / φ

emoji_responses = {
    "success": "✅ Operation completed!",
    "error": "❌ Something went wrong!",
    "warning": "⚠️ Please be careful!",
    "info": "ℹ️ For your information",
    "rocket": "🚀 Launching now!"
}

# Mathematical symbols
math_symbols = {
    "infinity": "",
    "sum": "",
    "product": "",
    "integral": "",
    "partial": "",
    "nabla": "",
    "element": "",
    "not_equal": "",
    "approximately": ""
}

# Multi-language strings
greetings = {
    "en": "Hello World",
    "es": "Hola Mundo",
    "fr": "Bonjour le Monde",
    "de": "Hallo Welt",
    "jp": "こんにちは世界",
    "cn": "你好世界",
    "ar": "مرحبا بالعالم",
    "ru": "Привет мир",
    "emoji": "👋 🌍"
}

Empty Code Blocks

# This block intentionally left almost empty

Performance Testing

Large Minified Code

// Minified code to test performance and readability
(function(){var a=function(b,c){return b+c},d=[1,2,3,4,5],e=d.map(function(b){return b*2}).filter(function(b){return b>5}).reduce(function(b,c){return b+c},0);console.log(e);var f={data:d,process:function(){return this.data.map(function(b){return{value:b,square:b*b,cube:b*b*b,sqrt:Math.sqrt(b)}})},analyze:function(){var b=this.process();return{min:Math.min.apply(Math,this.data),max:Math.max.apply(Math,this.data),sum:this.data.reduce(a,0),avg:this.data.reduce(a,0)/this.data.length,processed:b}}};console.log(f.analyze());for(var g=0;g<10;g++)console.log("Iteration:",g,"Result:",a(g,g*2))})();

Conclusion

This test document demonstrates our syntax highlighter handles:

✅ Multiple programming languages with proper highlighting ✅ Special characters and Unicode ✅ Very long lines and large code blocks ✅ Nested language blocks ✅ Edge cases and empty blocks ✅ Performance with minified code

All code blocks render correctly with:

  • Proper syntax highlighting
  • Copy functionality
  • Responsive design
  • Dark/light theme support
Share :LinkedIn