Markdown Code Highlighting and Syntax Features: Complete Guide for Enhanced Technical Documentation
Advanced Markdown code highlighting transforms technical documentation by providing visually distinct, language-specific syntax coloring and enhanced readability for code examples across programming languages and markup formats. By implementing proper syntax specification, custom highlighting themes, and interactive code features, technical writers can create compelling documentation that improves code comprehension while maintaining the simplicity and portability that makes Markdown an ideal format for technical content creation.
Why Master Code Highlighting in Markdown?
Professional code highlighting provides essential benefits for technical documentation:
- Enhanced Readability: Syntax coloring makes code structure and keywords immediately recognizable
- Language Context: Proper syntax specification helps readers understand the programming language being demonstrated
- Professional Presentation: Well-formatted code blocks create polished, publication-ready documentation
- Learning Acceleration: Visual differentiation of syntax elements speeds comprehension for learners
- Cross-Platform Consistency: Standardized highlighting works across different Markdown processors and platforms
Foundation Code Block Syntax
Basic Code Block Patterns
Understanding the fundamental approaches to creating code blocks in Markdown:
# Inline Code Examples
Use `backticks` for inline code within sentences. For example, the `console.log()` function outputs to the browser console.
# Fenced Code Blocks
Use triple backticks for multi-line code blocks:
```
function greetUser(name) {
console.log("Hello, " + name + "!");
}
greetUser("World");
```
# Indented Code Blocks
Alternatively, use 4-space indentation:
def calculate_sum(a, b):
return a + b
result = calculate_sum(10, 20)
print(f"Result: {result}")
# Language-Specific Highlighting
Specify the programming language after opening backticks:
```javascript
const API_URL = 'https://api.example.com';
async function fetchUserData(userId) {
try {
const response = await fetch(`${API_URL}/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const userData = await response.json();
return userData;
} catch (error) {
console.error('Failed to fetch user data:', error);
return null;
}
}
```
```python
import asyncio
import aiohttp
from typing import Optional, Dict, Any
class APIClient:
def __init__(self, base_url: str, timeout: int = 30):
self.base_url = base_url.rstrip('/')
self.timeout = aiohttp.ClientTimeout(total=timeout)
async def get_user(self, user_id: int) -> Optional[Dict[str, Any]]:
"""Fetch user data from the API"""
async with aiohttp.ClientSession(timeout=self.timeout) as session:
url = f"{self.base_url}/users/{user_id}"
try:
async with session.get(url) as response:
response.raise_for_status()
return await response.json()
except aiohttp.ClientError as e:
print(f"API request failed: {e}")
return None
# Usage example
async def main():
client = APIClient("https://api.example.com")
user_data = await client.get_user(123)
if user_data:
print(f"User: {user_data['name']}")
asyncio.run(main())
```
```go
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
type APIClient struct {
baseURL string
httpClient *http.Client
}
func NewAPIClient(baseURL string) *APIClient {
return &APIClient{
baseURL: baseURL,
httpClient: &http.Client{
Timeout: 30 * time.Second,
},
}
}
func (c *APIClient) GetUser(ctx context.Context, userID int) (*User, error) {
url := fmt.Sprintf("%s/users/%d", c.baseURL, userID)
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, fmt.Errorf("creating request: %w", err)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("making request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API error: %s", resp.Status)
}
var user User
if err := json.NewDecoder(resp.Body).Decode(&user); err != nil {
return nil, fmt.Errorf("decoding response: %w", err)
}
return &user, nil
}
func main() {
client := NewAPIClient("https://api.example.com")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
user, err := client.GetUser(ctx, 123)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("User: %s (%s)\n", user.Name, user.Email)
}
```
Advanced Language Support
Comprehensive syntax highlighting for specialized languages and formats:
# Configuration Files
## YAML Configuration
```yaml
# Application Configuration
app:
name: "Documentation System"
version: "2.1.0"
environment: production
database:
host: localhost
port: 5432
name: docs_db
credentials:
username: ${DB_USER}
password: ${DB_PASS}
cache:
redis:
url: "redis://localhost:6379/0"
max_connections: 10
logging:
level: info
format: json
outputs:
- console
- file: /var/log/app.log
```
## JSON Configuration
```json
{
"name": "markdown-docs",
"version": "1.0.0",
"description": "Advanced Markdown documentation system",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"build": "webpack --mode production",
"test": "jest --coverage"
},
"dependencies": {
"express": "^4.18.0",
"markdown-it": "^13.0.0",
"highlight.js": "^11.7.0"
},
"devDependencies": {
"nodemon": "^2.0.0",
"jest": "^29.0.0",
"webpack": "^5.70.0"
},
"engines": {
"node": ">=16.0.0",
"npm": ">=8.0.0"
}
}
```
## TOML Configuration
```toml
[package]
name = "markdown-processor"
version = "0.1.0"
edition = "2021"
authors = ["Technical Writer <[email protected]>"]
description = "High-performance Markdown processing library"
[dependencies]
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
pulldown-cmark = "0.9"
syntect = "5.0"
[dev-dependencies]
criterion = "0.4"
tempfile = "3.0"
[[bin]]
name = "markdown-cli"
path = "src/main.rs"
[profile.release]
opt-level = 3
lto = true
codegen-units = 1
```
# Database Queries
## SQL Examples
```sql
-- Complex user analytics query
WITH user_activity AS (
SELECT
u.id,
u.username,
u.email,
COUNT(DISTINCT s.id) as session_count,
COUNT(DISTINCT p.id) as page_views,
MAX(s.created_at) as last_activity,
AVG(s.duration) as avg_session_duration
FROM users u
LEFT JOIN sessions s ON u.id = s.user_id
LEFT JOIN page_views p ON s.id = p.session_id
WHERE u.created_at >= '2025-01-01'
GROUP BY u.id, u.username, u.email
),
engagement_metrics AS (
SELECT
id,
username,
email,
session_count,
page_views,
last_activity,
avg_session_duration,
CASE
WHEN session_count >= 10 AND page_views >= 50 THEN 'High'
WHEN session_count >= 5 AND page_views >= 20 THEN 'Medium'
ELSE 'Low'
END as engagement_level
FROM user_activity
)
SELECT
engagement_level,
COUNT(*) as user_count,
AVG(session_count) as avg_sessions,
AVG(page_views) as avg_page_views,
AVG(avg_session_duration) as avg_duration_minutes
FROM engagement_metrics
GROUP BY engagement_level
ORDER BY
CASE engagement_level
WHEN 'High' THEN 1
WHEN 'Medium' THEN 2
WHEN 'Low' THEN 3
END;
```
## MongoDB Aggregation
```javascript
db.users.aggregate([
{
$match: {
created_at: { $gte: new Date("2025-01-01") },
status: "active"
}
},
{
$lookup: {
from: "sessions",
localField: "_id",
foreignField: "user_id",
as: "sessions"
}
},
{
$lookup: {
from: "page_views",
localField: "sessions._id",
foreignField: "session_id",
as: "page_views"
}
},
{
$addFields: {
session_count: { $size: "$sessions" },
total_page_views: { $size: "$page_views" },
avg_session_duration: {
$avg: "$sessions.duration"
},
last_activity: {
$max: "$sessions.created_at"
}
}
},
{
$addFields: {
engagement_level: {
$switch: {
branches: [
{
case: {
$and: [
{ $gte: ["$session_count", 10] },
{ $gte: ["$total_page_views", 50] }
]
},
then: "High"
},
{
case: {
$and: [
{ $gte: ["$session_count", 5] },
{ $gte: ["$total_page_views", 20] }
]
},
then: "Medium"
}
],
default: "Low"
}
}
}
},
{
$group: {
_id: "$engagement_level",
user_count: { $sum: 1 },
avg_sessions: { $avg: "$session_count" },
avg_page_views: { $avg: "$total_page_views" },
avg_duration: { $avg: "$avg_session_duration" }
}
},
{
$sort: {
_id: 1
}
}
]);
```
Language-Specific Highlighting Techniques
Custom Syntax Extensions
Implementing advanced highlighting for domain-specific languages and frameworks:
# Infrastructure as Code
## Terraform Configuration
```hcl
# AWS infrastructure definition
terraform {
required_version = ">= 1.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
backend "s3" {
bucket = "terraform-state-bucket"
key = "infrastructure/terraform.tfstate"
region = "us-west-2"
encrypt = true
dynamodb_table = "terraform-locks"
}
}
provider "aws" {
region = var.aws_region
default_tags {
tags = {
Project = "Documentation System"
Environment = var.environment
ManagedBy = "Terraform"
}
}
}
# VPC Configuration
resource "aws_vpc" "main" {
cidr_block = var.vpc_cidr
enable_dns_hostnames = true
enable_dns_support = true
tags = {
Name = "${var.project_name}-vpc"
}
}
resource "aws_internet_gateway" "main" {
vpc_id = aws_vpc.main.id
tags = {
Name = "${var.project_name}-igw"
}
}
# Public Subnets
resource "aws_subnet" "public" {
count = length(var.availability_zones)
vpc_id = aws_vpc.main.id
cidr_block = cidrsubnet(var.vpc_cidr, 8, count.index)
availability_zone = var.availability_zones[count.index]
map_public_ip_on_launch = true
tags = {
Name = "${var.project_name}-public-${count.index + 1}"
Type = "Public"
}
}
# Application Load Balancer
resource "aws_lb" "main" {
name = "${var.project_name}-alb"
internal = false
load_balancer_type = "application"
security_groups = [aws_security_group.alb.id]
subnets = aws_subnet.public[*].id
enable_deletion_protection = var.environment == "production"
tags = {
Name = "${var.project_name}-alb"
}
}
# ECS Cluster
resource "aws_ecs_cluster" "main" {
name = "${var.project_name}-cluster"
configuration {
execute_command_configuration {
logging = "OVERRIDE"
log_configuration {
cloud_watch_log_group_name = aws_cloudwatch_log_group.ecs.name
}
}
}
setting {
name = "containerInsights"
value = "enabled"
}
tags = {
Name = "${var.project_name}-cluster"
}
}
```
## Docker Compose
```yaml
version: '3.8'
services:
# Application Service
app:
build:
context: .
dockerfile: Dockerfile
args:
- NODE_ENV=production
ports:
- "3000:3000"
environment:
- NODE_ENV=production
- DATABASE_URL=postgresql://postgres:${POSTGRES_PASSWORD}@db:5432/docs_db
- REDIS_URL=redis://redis:6379/0
- JWT_SECRET=${JWT_SECRET}
depends_on:
db:
condition: service_healthy
redis:
condition: service_started
volumes:
- ./uploads:/app/uploads
- ./logs:/app/logs
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
restart: unless-stopped
networks:
- app-network
# Database Service
db:
image: postgres:15-alpine
environment:
- POSTGRES_DB=docs_db
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init-scripts:/docker-entrypoint-initdb.d
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d docs_db"]
interval: 10s
timeout: 5s
retries: 5
restart: unless-stopped
networks:
- app-network
# Redis Cache Service
redis:
image: redis:7-alpine
command: redis-server --appendonly yes --requirepass ${REDIS_PASSWORD}
ports:
- "6379:6379"
volumes:
- redis_data:/data
restart: unless-stopped
networks:
- app-network
# Nginx Reverse Proxy
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
- ./nginx/ssl:/etc/nginx/ssl:ro
- ./static:/var/www/static:ro
depends_on:
- app
restart: unless-stopped
networks:
- app-network
# Monitoring
prometheus:
image: prom/prometheus:latest
ports:
- "9090:9090"
volumes:
- ./monitoring/prometheus.yml:/etc/prometheus/prometheus.yml:ro
- prometheus_data:/prometheus
command:
- '--config.file=/etc/prometheus/prometheus.yml'
- '--storage.tsdb.path=/prometheus'
- '--web.console.libraries=/etc/prometheus/console_libraries'
- '--web.console.templates=/etc/prometheus/consoles'
- '--storage.tsdb.retention.time=200h'
- '--web.enable-lifecycle'
restart: unless-stopped
networks:
- app-network
volumes:
postgres_data:
driver: local
redis_data:
driver: local
prometheus_data:
driver: local
networks:
app-network:
driver: bridge
ipam:
config:
- subnet: 172.20.0.0/16
```
# Shell Scripts and DevOps
## Bash Deployment Script
```bash
#!/bin/bash
# Advanced deployment script with error handling and rollback
set -euo pipefail
# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_NAME="${PROJECT_NAME:-docs-system}"
ENVIRONMENT="${ENVIRONMENT:-staging}"
BUILD_NUMBER="${BUILD_NUMBER:-$(date +%Y%m%d-%H%M%S)}"
DEPLOY_TIMEOUT="${DEPLOY_TIMEOUT:-300}"
# Color codes for output
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly NC='\033[0m' # No Color
# Logging functions
log_info() {
echo -e "${BLUE}[INFO]${NC} $1" >&2
}
log_success() {
echo -e "${GREEN}[SUCCESS]${NC} $1" >&2
}
log_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1" >&2
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1" >&2
}
# Error handling
cleanup_on_error() {
local exit_code=$?
log_error "Deployment failed with exit code $exit_code"
if [[ -n "${PREVIOUS_VERSION:-}" ]]; then
log_info "Initiating rollback to previous version: $PREVIOUS_VERSION"
rollback_deployment "$PREVIOUS_VERSION"
fi
exit $exit_code
}
trap cleanup_on_error ERR
# Health check function
check_service_health() {
local service_url="$1"
local max_attempts="${2:-30}"
local attempt=1
log_info "Checking service health at $service_url"
while [[ $attempt -le $max_attempts ]]; do
if curl -sf --connect-timeout 5 --max-time 10 "$service_url" > /dev/null; then
log_success "Service is healthy"
return 0
fi
log_info "Health check attempt $attempt/$max_attempts failed, waiting..."
sleep 10
((attempt++))
done
log_error "Service failed health checks after $max_attempts attempts"
return 1
}
# Deployment function
deploy_application() {
local version="$1"
log_info "Starting deployment of version $version to $ENVIRONMENT"
# Pull latest images
log_info "Pulling Docker images..."
docker-compose -f "docker-compose.${ENVIRONMENT}.yml" pull
# Run database migrations if needed
if [[ -f "migrations/pending.txt" ]]; then
log_info "Running database migrations..."
docker-compose -f "docker-compose.${ENVIRONMENT}.yml" run --rm app npm run migrate
fi
# Deploy with zero-downtime
log_info "Deploying services..."
docker-compose -f "docker-compose.${ENVIRONMENT}.yml" up -d --remove-orphans
# Wait for services to be ready
local health_url="http://localhost:3000/health"
if ! check_service_health "$health_url" 30; then
log_error "Application health check failed"
return 1
fi
log_success "Deployment completed successfully"
}
# Rollback function
rollback_deployment() {
local target_version="$1"
log_warning "Rolling back to version $target_version"
# Set image tags to previous version
export IMAGE_TAG="$target_version"
# Deploy previous version
docker-compose -f "docker-compose.${ENVIRONMENT}.yml" up -d --remove-orphans
# Verify rollback
local health_url="http://localhost:3000/health"
if check_service_health "$health_url" 15; then
log_success "Rollback completed successfully"
else
log_error "Rollback failed - manual intervention required"
exit 1
fi
}
# Pre-deployment checks
run_pre_deployment_checks() {
log_info "Running pre-deployment checks..."
# Check Docker daemon
if ! docker info > /dev/null 2>&1; then
log_error "Docker daemon is not running"
exit 1
fi
# Check available disk space (minimum 2GB)
local available_space
available_space=$(df / | tail -1 | awk '{print $4}')
if [[ $available_space -lt 2000000 ]]; then
log_warning "Low disk space detected: ${available_space}KB available"
fi
# Check if services are running
if docker-compose -f "docker-compose.${ENVIRONMENT}.yml" ps | grep -q "Up"; then
PREVIOUS_VERSION=$(docker-compose -f "docker-compose.${ENVIRONMENT}.yml" images | grep app | awk '{print $2}' | head -1)
log_info "Previous version detected: ${PREVIOUS_VERSION:-unknown}"
fi
log_success "Pre-deployment checks passed"
}
# Post-deployment verification
run_post_deployment_verification() {
log_info "Running post-deployment verification..."
# Test critical endpoints
local base_url="http://localhost:3000"
local endpoints=("/health" "/api/status" "/api/version")
for endpoint in "${endpoints[@]}"; do
if ! curl -sf --connect-timeout 5 "$base_url$endpoint" > /dev/null; then
log_error "Endpoint $endpoint is not responding"
return 1
fi
done
# Test database connectivity
if ! docker-compose -f "docker-compose.${ENVIRONMENT}.yml" exec -T db pg_isready -U postgres; then
log_error "Database connectivity test failed"
return 1
fi
log_success "Post-deployment verification completed"
}
# Main deployment workflow
main() {
log_info "Starting deployment workflow for $PROJECT_NAME ($ENVIRONMENT)"
log_info "Build number: $BUILD_NUMBER"
run_pre_deployment_checks
deploy_application "$BUILD_NUMBER"
run_post_deployment_verification
# Clean up old images
log_info "Cleaning up old Docker images..."
docker image prune -f
log_success "Deployment workflow completed successfully!"
log_info "Application is now running version $BUILD_NUMBER"
}
# Script entry point
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi
```
Interactive Code Features
Code Block Enhancements
Advanced techniques for creating interactive and enhanced code presentations:
# Enhanced Code Presentations
## Code with Line Numbers and Highlighting
```javascript {linenos=true,hl_lines=[8,"15-17"],linenostart=1}
// Advanced API client with retry logic and exponential backoff
class ResilientAPIClient {
constructor(baseURL, options = {}) {
this.baseURL = baseURL;
this.maxRetries = options.maxRetries || 3;
this.baseDelay = options.baseDelay || 1000;
this.maxDelay = options.maxDelay || 30000;
this.timeout = options.timeout || 10000; // Highlighted line
// Create axios instance with default config
this.client = axios.create({
baseURL: this.baseURL,
timeout: this.timeout,
headers: {
'Content-Type': 'application/json',
'User-Agent': 'ResilientAPIClient/1.0.0' // Highlighted block start
}
}); // Highlighted block end
}
async executeWithRetry(requestFn) {
let lastError;
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
try {
const result = await requestFn();
return result;
} catch (error) {
lastError = error;
if (attempt === this.maxRetries) {
break;
}
// Calculate delay with exponential backoff
const delay = Math.min(
this.baseDelay * Math.pow(2, attempt),
this.maxDelay
);
console.log(`Request failed (attempt ${attempt + 1}), retrying in ${delay}ms...`);
await this.sleep(delay);
}
}
throw lastError;
}
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
```
## Tabbed Code Examples
```markdown
<!-- Tab Group: API Implementation -->
{% tabs %}
{% tab title="Node.js" %}
```javascript
const express = require('express');
const helmet = require('helmet');
const compression = require('compression');
const rateLimit = require('express-rate-limit');
const app = express();
// Security middleware
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
scriptSrc: ["'self'"],
imgSrc: ["'self'", "data:", "https:"],
},
},
}));
// Rate limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: {
error: 'Too many requests from this IP, please try again later.'
}
});
app.use(limiter);
app.use(compression());
app.use(express.json({ limit: '10mb' }));
// API Routes
app.get('/api/users/:id', async (req, res) => {
try {
const userId = parseInt(req.params.id);
const user = await getUserById(userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json({
success: true,
data: user
});
} catch (error) {
console.error('Error fetching user:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
```
{% endtab %}
{% tab title="Python FastAPI" %}
```python
from fastapi import FastAPI, HTTPException, Depends, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi_limiter import FastAPILimiter
from fastapi_limiter.depends import RateLimiter
import redis.asyncio as redis
from pydantic import BaseModel
from typing import Optional
import logging
app = FastAPI(
title="Documentation API",
description="Advanced API for documentation management",
version="2.0.0"
)
# Middleware
app.add_middleware(GZipMiddleware, minimum_size=1000)
app.add_middleware(
CORSMiddleware,
allow_origins=["https://docs.example.com"],
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["*"],
)
# Security
security = HTTPBearer()
class User(BaseModel):
id: int
name: str
email: str
is_active: bool = True
class UserResponse(BaseModel):
success: bool
data: User
@app.on_event("startup")
async def startup():
redis_client = redis.from_url("redis://localhost", encoding="utf-8", decode_responses=True)
await FastAPILimiter.init(redis_client)
async def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
# Token verification logic here
if not credentials.credentials:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials"
)
return credentials.credentials
@app.get("/api/users/{user_id}",
response_model=UserResponse,
dependencies=[Depends(RateLimiter(times=10, seconds=60))])
async def get_user(
user_id: int,
token: str = Depends(verify_token)
) -> UserResponse:
"""
Retrieve user information by ID.
- **user_id**: The ID of the user to retrieve
- **Returns**: User information with success status
"""
try:
user = await get_user_by_id(user_id)
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
return UserResponse(success=True, data=user)
except Exception as e:
logging.error(f"Error fetching user {user_id}: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Internal server error"
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
```
{% endtab %}
{% tab title="Go Gin" %}
```go
package main
import (
"context"
"fmt"
"net/http"
"strconv"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis_rate/v10"
"github.com/go-redis/redis/v8"
"go.uber.org/zap"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
IsActive bool `json:"is_active"`
}
type UserResponse struct {
Success bool `json:"success"`
Data User `json:"data"`
}
type APIError struct {
Error string `json:"error"`
}
func main() {
// Initialize logger
logger, _ := zap.NewProduction()
defer logger.Sync()
// Initialize Redis for rate limiting
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
limiter := redis_rate.NewLimiter(rdb)
// Initialize Gin router
router := gin.New()
// Middleware
router.Use(gin.LoggerWithZap(logger, time.RFC3339, true))
router.Use(gin.RecoveryWithZap(logger, true))
router.Use(gzip.Gzip(gzip.DefaultCompression))
// CORS configuration
config := cors.DefaultConfig()
config.AllowOrigins = []string{"https://docs.example.com"}
config.AllowCredentials = true
router.Use(cors.New(config))
// Rate limiting middleware
rateLimitMiddleware := func(c *gin.Context) {
ctx := context.Background()
key := "rate_limit:" + c.ClientIP()
res, err := limiter.Allow(ctx, key, redis_rate.PerMinute(60))
if err != nil {
logger.Error("Rate limiting error", zap.Error(err))
c.Next()
return
}
if res.Allowed == 0 {
c.JSON(http.StatusTooManyRequests, APIError{
Error: "Rate limit exceeded",
})
c.Abort()
return
}
c.Next()
}
// Authentication middleware
authMiddleware := func(c *gin.Context) {
token := c.GetHeader("Authorization")
if token == "" {
c.JSON(http.StatusUnauthorized, APIError{
Error: "Authorization header required",
})
c.Abort()
return
}
// Token validation logic here
// For demo purposes, we'll just check if it's not empty
c.Next()
}
// API Routes
api := router.Group("/api", rateLimitMiddleware, authMiddleware)
{
api.GET("/users/:id", getUserHandler(logger))
}
// Start server
port := "8080"
logger.Info("Starting server", zap.String("port", port))
if err := router.Run(":" + port); err != nil {
logger.Fatal("Failed to start server", zap.Error(err))
}
}
func getUserHandler(logger *zap.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
userIDStr := c.Param("id")
userID, err := strconv.Atoi(userIDStr)
if err != nil {
c.JSON(http.StatusBadRequest, APIError{
Error: "Invalid user ID",
})
return
}
// Mock user retrieval
user, err := getUserByID(userID)
if err != nil {
logger.Error("Error fetching user",
zap.Int("user_id", userID),
zap.Error(err),
)
c.JSON(http.StatusInternalServerError, APIError{
Error: "Internal server error",
})
return
}
if user == nil {
c.JSON(http.StatusNotFound, APIError{
Error: "User not found",
})
return
}
c.JSON(http.StatusOK, UserResponse{
Success: true,
Data: *user,
})
}
}
func getUserByID(id int) (*User, error) {
// Mock implementation
if id == 123 {
return &User{
ID: 123,
Name: "John Doe",
Email: "[email protected]",
IsActive: true,
}, nil
}
return nil, nil
}
```
{% endtab %}
{% endtabs %}
Code Annotation and Documentation
Advanced techniques for creating comprehensive code documentation:
# Annotated Code Examples
## Function Documentation with Examples
```python
def process_markdown_with_highlighting(
content: str,
language: str = "markdown",
theme: str = "default",
line_numbers: bool = True,
highlight_lines: Optional[List[int]] = None
) -> Dict[str, Any]:
"""
Process Markdown content with advanced syntax highlighting.
This function takes raw Markdown content and applies sophisticated
syntax highlighting with customizable themes and features.
Args:
content (str): The raw Markdown content to process
language (str, optional): Programming language for syntax highlighting.
Defaults to "markdown". Supported languages include:
- markdown, html, css, javascript, python, go, rust, etc.
theme (str, optional): Color theme for highlighting.
Defaults to "default". Available themes:
- default, dark, light, github, monokai, solarized
line_numbers (bool, optional): Whether to show line numbers.
Defaults to True.
highlight_lines (List[int], optional): List of line numbers to highlight.
Defaults to None (no lines highlighted).
Returns:
Dict[str, Any]: Processing result containing:
- 'html': Rendered HTML with syntax highlighting
- 'metadata': Processing metadata (language, theme, etc.)
- 'statistics': Processing statistics (line count, etc.)
Raises:
ValueError: If the specified language is not supported
SyntaxError: If the content contains invalid syntax
Example:
>>> content = '''
... ```python
... def hello_world():
... print("Hello, World!")
... ```
... '''
>>> result = process_markdown_with_highlighting(
... content=content,
... language="python",
... theme="github",
... highlight_lines=[2]
... )
>>> print(result['html'])
<div class="highlight github-theme">
<pre><code class="language-python">
<span class="lineno">1</span><span class="k">def</span> <span class="nf">hello_world</span>():
<span class="lineno highlight">2</span> <span class="nb">print</span>(<span class="s">"Hello, World!"</span>)
</code></pre>
</div>
Note:
The function automatically detects code blocks within Markdown
and applies appropriate syntax highlighting. Custom themes can
be added by extending the theme configuration.
"""
# Input validation
if not isinstance(content, str):
raise TypeError("Content must be a string")
if language not in SUPPORTED_LANGUAGES:
raise ValueError(f"Unsupported language: {language}")
# Initialize processor with theme
processor = MarkdownProcessor(theme=theme)
# Configure highlighting options
options = HighlightingOptions(
show_line_numbers=line_numbers,
highlight_lines=highlight_lines or [],
theme=theme
)
try:
# Process the content
result = processor.process(content, language, options)
# Generate metadata
metadata = {
'language': language,
'theme': theme,
'line_count': content.count('\n') + 1,
'processing_time': result.processing_time,
'features_enabled': {
'line_numbers': line_numbers,
'highlighted_lines': len(highlight_lines or [])
}
}
# Compile statistics
statistics = {
'total_lines': metadata['line_count'],
'highlighted_lines': len(highlight_lines or []),
'processing_duration_ms': metadata['processing_time'],
'html_size_bytes': len(result.html.encode('utf-8'))
}
return {
'html': result.html,
'metadata': metadata,
'statistics': statistics
}
except Exception as e:
# Log the error for debugging
logger.error(f"Failed to process markdown content: {e}")
# Re-raise with context
raise SyntaxError(f"Content processing failed: {e}") from e
# Example usage with error handling
def main():
"""Example usage of the markdown processor."""
sample_content = '''
# Sample Document
Here's a Python function example:
```python
def fibonacci(n: int) -> int:
"""Calculate the nth Fibonacci number."""
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
# Generate first 10 Fibonacci numbers
for i in range(10):
print(f"F({i}) = {fibonacci(i)}")
```
And here's a JavaScript version:
```javascript
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
// Generate first 10 Fibonacci numbers
for (let i = 0; i < 10; i++) {
console.log(`F(${i}) = ${fibonacci(i)}`);
}
```
'''
try:
result = process_markdown_with_highlighting(
content=sample_content,
theme="github",
highlight_lines=[5, 6, 7] # Highlight function definition
)
print("Processing successful!")
print(f"Generated HTML: {len(result['html'])} bytes")
print(f"Processing time: {result['statistics']['processing_duration_ms']}ms")
except (ValueError, SyntaxError) as e:
print(f"Processing error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
if __name__ == "__main__":
main()
```
Advanced Highlighting Configuration
Theme Customization and Color Schemes
Professional approaches to customizing syntax highlighting themes:
# Custom Theme Configuration
## CSS Theme Definition
```css
/* GitHub-inspired syntax highlighting theme */
.highlight.github-theme {
background-color: #f6f8fa;
border: 1px solid #d1d5da;
border-radius: 6px;
padding: 16px;
overflow-x: auto;
font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
font-size: 14px;
line-height: 1.45;
}
.highlight.github-theme code {
background-color: transparent;
border: none;
padding: 0;
font-size: inherit;
color: inherit;
white-space: pre;
word-wrap: normal;
}
/* Line numbers */
.highlight.github-theme .lineno {
color: #656d76;
user-select: none;
margin-right: 16px;
padding-right: 16px;
border-right: 1px solid #d1d5da;
display: inline-block;
min-width: 40px;
text-align: right;
}
.highlight.github-theme .lineno.highlight {
background-color: #fff8c5;
border-color: #f9c513;
}
/* Syntax highlighting colors */
.highlight.github-theme .k { color: #d73a49; } /* Keywords */
.highlight.github-theme .kn { color: #d73a49; } /* Keyword.Namespace */
.highlight.github-theme .kp { color: #d73a49; } /* Keyword.Pseudo */
.highlight.github-theme .kr { color: #d73a49; } /* Keyword.Reserved */
.highlight.github-theme .kt { color: #d73a49; } /* Keyword.Type */
.highlight.github-theme .s { color: #032f62; } /* Strings */
.highlight.github-theme .s1 { color: #032f62; } /* String.Single */
.highlight.github-theme .s2 { color: #032f62; } /* String.Double */
.highlight.github-theme .se { color: #032f62; } /* String.Escape */
.highlight.github-theme .si { color: #032f62; } /* String.Interpol */
.highlight.github-theme .nb { color: #005cc5; } /* Name.Builtin */
.highlight.github-theme .nf { color: #6f42c1; } /* Name.Function */
.highlight.github-theme .nc { color: #6f42c1; } /* Name.Class */
.highlight.github-theme .nn { color: #6f42c1; } /* Name.Namespace */
.highlight.github-theme .m { color: #005cc5; } /* Numbers */
.highlight.github-theme .mi { color: #005cc5; } /* Number.Integer */
.highlight.github-theme .mf { color: #005cc5; } /* Number.Float */
.highlight.github-theme .c { color: #6a737d; font-style: italic; } /* Comments */
.highlight.github-theme .c1 { color: #6a737d; font-style: italic; } /* Comment.Single */
.highlight.github-theme .cm { color: #6a737d; font-style: italic; } /* Comment.Multiline */
.highlight.github-theme .o { color: #d73a49; } /* Operators */
.highlight.github-theme .p { color: #24292e; } /* Punctuation */
/* Dark theme variant */
.highlight.github-dark-theme {
background-color: #0d1117;
border: 1px solid #30363d;
color: #f0f6fc;
}
.highlight.github-dark-theme .lineno {
color: #7d8590;
border-right-color: #30363d;
}
.highlight.github-dark-theme .lineno.highlight {
background-color: #ffd33d1a;
border-color: #ffd33d;
}
.highlight.github-dark-theme .k { color: #ff7b72; }
.highlight.github-dark-theme .s { color: #a5d6ff; }
.highlight.github-dark-theme .nb { color: #79c0ff; }
.highlight.github-dark-theme .nf { color: #d2a8ff; }
.highlight.github-dark-theme .nc { color: #d2a8ff; }
.highlight.github-dark-theme .m { color: #79c0ff; }
.highlight.github-dark-theme .c { color: #8b949e; }
.highlight.github-dark-theme .o { color: #ff7b72; }
.highlight.github-dark-theme .p { color: #f0f6fc; }
/* Interactive features */
.highlight pre {
position: relative;
}
.highlight .copy-button {
position: absolute;
top: 8px;
right: 8px;
background: #24292e;
color: #fff;
border: none;
border-radius: 4px;
padding: 4px 8px;
font-size: 12px;
cursor: pointer;
opacity: 0;
transition: opacity 0.2s ease;
}
.highlight:hover .copy-button {
opacity: 1;
}
.highlight .copy-button:hover {
background: #1b1f23;
}
.highlight .copy-button.copied {
background: #28a745;
}
/* Responsive design */
@media (max-width: 768px) {
.highlight {
font-size: 12px;
padding: 12px;
}
.highlight .lineno {
min-width: 30px;
margin-right: 8px;
padding-right: 8px;
}
}
/* Print styles */
@media print {
.highlight {
border: 1px solid #000;
background: #fff !important;
color: #000 !important;
}
.highlight * {
color: #000 !important;
background: transparent !important;
}
.highlight .copy-button {
display: none;
}
}
```
## JavaScript Enhancement
```javascript
/**
* Enhanced code block functionality with copy, expand, and interaction features
*/
class CodeBlockEnhancer {
constructor(options = {}) {
this.options = {
enableCopy: true,
enableLineNumbers: true,
enableHighlighting: true,
enableExpansion: true,
maxHeight: 400, // pixels
...options
};
this.clipboard = null;
this.init();
}
async init() {
// Initialize clipboard API if available
if (navigator.clipboard) {
this.clipboard = navigator.clipboard;
}
// Process all code blocks
this.enhanceCodeBlocks();
// Set up event listeners
this.setupEventListeners();
}
enhanceCodeBlocks() {
const codeBlocks = document.querySelectorAll('pre code');
codeBlocks.forEach((block, index) => {
this.enhanceCodeBlock(block, index);
});
}
enhanceCodeBlock(codeBlock, index) {
const pre = codeBlock.parentElement;
const wrapper = document.createElement('div');
wrapper.className = 'enhanced-code-block';
wrapper.dataset.blockId = index;
// Wrap the pre element
pre.parentElement.insertBefore(wrapper, pre);
wrapper.appendChild(pre);
// Add toolbar
if (this.options.enableCopy) {
this.addCopyButton(wrapper, codeBlock);
}
// Add line numbers if not present
if (this.options.enableLineNumbers && !codeBlock.querySelector('.lineno')) {
this.addLineNumbers(codeBlock);
}
// Add expansion for long code blocks
if (this.options.enableExpansion) {
this.addExpansionFeature(wrapper, pre);
}
// Add language detection and highlighting
if (this.options.enableHighlighting) {
this.enhanceSyntaxHighlighting(codeBlock);
}
}
addCopyButton(wrapper, codeBlock) {
const toolbar = document.createElement('div');
toolbar.className = 'code-toolbar';
const copyButton = document.createElement('button');
copyButton.className = 'copy-button';
copyButton.innerHTML = `
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 010 1.5h-1.5a.25.25 0 00-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 00.25-.25v-1.5a.75.75 0 011.5 0v1.5A1.75 1.75 0 019.25 16h-7.5A1.75 1.75 0 010 14.25v-7.5z"/>
<path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0114.25 11h-7.5A1.75 1.75 0 015 9.25v-7.5zm1.75-.25a.25.25 0 00-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 00.25-.25v-7.5a.25.25 0 00-.25-.25h-7.5z"/>
</svg>
Copy
`;
copyButton.title = 'Copy code to clipboard';
copyButton.addEventListener('click', () => {
this.copyCode(codeBlock, copyButton);
});
toolbar.appendChild(copyButton);
wrapper.insertBefore(toolbar, wrapper.firstChild);
}
async copyCode(codeBlock, button) {
// Get the code text without line numbers
let code = codeBlock.textContent;
// Remove line numbers if present
code = code.replace(/^\s*\d+\s*/gm, '');
try {
if (this.clipboard) {
await this.clipboard.writeText(code);
} else {
// Fallback for older browsers
this.fallbackCopy(code);
}
// Visual feedback
const originalText = button.innerHTML;
button.innerHTML = `
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
<path d="M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z"/>
</svg>
Copied!
`;
button.classList.add('copied');
setTimeout(() => {
button.innerHTML = originalText;
button.classList.remove('copied');
}, 2000);
} catch (error) {
console.error('Failed to copy code:', error);
// Show error feedback
button.innerHTML = 'Copy failed';
setTimeout(() => {
button.innerHTML = originalText;
}, 2000);
}
}
fallbackCopy(text) {
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
textArea.style.left = '-999999px';
textArea.style.top = '-999999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
document.execCommand('copy');
} catch (error) {
throw new Error('Clipboard not supported');
} finally {
document.body.removeChild(textArea);
}
}
addLineNumbers(codeBlock) {
const lines = codeBlock.textContent.split('\n');
const numberedLines = lines.map((line, index) => {
const lineNumber = index + 1;
return `<span class="lineno">${lineNumber}</span>${line}`;
});
codeBlock.innerHTML = numberedLines.join('\n');
}
addExpansionFeature(wrapper, pre) {
const maxHeight = this.options.maxHeight;
if (pre.scrollHeight > maxHeight) {
pre.style.maxHeight = maxHeight + 'px';
pre.style.overflow = 'hidden';
const expandButton = document.createElement('button');
expandButton.className = 'expand-button';
expandButton.textContent = 'Show more';
expandButton.addEventListener('click', () => {
if (pre.style.maxHeight) {
pre.style.maxHeight = '';
pre.style.overflow = 'auto';
expandButton.textContent = 'Show less';
} else {
pre.style.maxHeight = maxHeight + 'px';
pre.style.overflow = 'hidden';
expandButton.textContent = 'Show more';
}
});
wrapper.appendChild(expandButton);
}
}
enhanceSyntaxHighlighting(codeBlock) {
// Detect language if not specified
const pre = codeBlock.parentElement;
let language = this.detectLanguage(codeBlock);
if (language && !pre.classList.contains('language-' + language)) {
pre.classList.add('language-' + language);
codeBlock.classList.add('language-' + language);
}
}
detectLanguage(codeBlock) {
const code = codeBlock.textContent;
// Simple language detection patterns
const patterns = {
javascript: /(?:function|const|let|var|=>|\.js)/,
python: /(?:def |import |from |print\(|\.py)/,
html: /<\w+[^>]*>/,
css: /\{[^}]*:[^}]*\}/,
json: /^\s*[\{\[]/,
bash: /^\s*(?:\$|#)/,
sql: /(?:SELECT|FROM|WHERE|INSERT|UPDATE|DELETE)/i
};
for (const [lang, pattern] of Object.entries(patterns)) {
if (pattern.test(code)) {
return lang;
}
}
return null;
}
setupEventListeners() {
// Keyboard shortcuts
document.addEventListener('keydown', (event) => {
// Ctrl/Cmd + C on focused code block
if ((event.ctrlKey || event.metaKey) && event.key === 'c') {
const focused = document.activeElement;
if (focused && focused.closest('.enhanced-code-block')) {
event.preventDefault();
const codeBlock = focused.closest('.enhanced-code-block').querySelector('code');
const copyButton = focused.closest('.enhanced-code-block').querySelector('.copy-button');
if (codeBlock && copyButton) {
this.copyCode(codeBlock, copyButton);
}
}
}
});
// Make code blocks focusable for keyboard navigation
document.querySelectorAll('.enhanced-code-block pre').forEach(pre => {
pre.setAttribute('tabindex', '0');
pre.setAttribute('role', 'region');
pre.setAttribute('aria-label', 'Code example');
});
}
}
// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
new CodeBlockEnhancer({
enableCopy: true,
enableLineNumbers: true,
enableExpansion: true,
maxHeight: 400
});
});
// Export for module systems
if (typeof module !== 'undefined' && module.exports) {
module.exports = CodeBlockEnhancer;
}
```
Integration with Documentation Systems
Code highlighting systems integrate seamlessly with comprehensive documentation workflows. When combined with table accessibility and structured data presentation, enhanced code blocks provide complete technical documentation experiences that serve developers with varying needs and assistive technology requirements while maintaining consistent presentation standards.
For sophisticated content management, code highlighting works effectively with performance optimization systems to ensure that syntax highlighting processing doesn’t impact page load times, implementing efficient caching strategies and lazy loading techniques for code-heavy documentation platforms.
When building comprehensive documentation architectures, code highlighting complements custom HTML components and extensions by providing specialized code presentation components that integrate seamlessly with interactive documentation features while maintaining the simplicity of Markdown authoring workflows.
Platform-Specific Implementation
Advanced integration techniques for popular documentation platforms:
# Platform Integration Examples
## Jekyll Integration
```yaml
# _config.yml - Jekyll configuration for enhanced code highlighting
highlighter: rouge
markdown: kramdown
kramdown:
input: GFM
syntax_highlighter: rouge
syntax_highlighter_opts:
line_numbers: true
tab_width: 4
wrap: false
bold_every: 5
plugins:
- jekyll-sitemap
- jekyll-feed
- rouge-themes
rouge:
themes:
- github
- monokai
- solarized
collections:
code_examples:
output: true
permalink: /:collection/:name/
defaults:
- scope:
path: "_code_examples"
type: "code_examples"
values:
layout: "code_example"
syntax_highlighting: true
```
## Hugo Integration
```yaml
# config.yaml - Hugo configuration for code highlighting
markup:
goldmark:
renderer:
unsafe: true
highlight:
lineNos: true
lineNumbersInTable: true
tabWidth: 4
style: github
noClasses: false
anchorLineNos: false
codeFences: true
guessSyntax: true
hl_Lines: ""
params:
code:
copy: true
maxShownLines: 50
theme: "github"
themes:
- github
- github-dark
- monokai
- solarized-dark
- solarized-light
menu:
main:
- name: "Code Examples"
url: "/examples/"
weight: 30
```
## GitBook Integration
```javascript
// book.json - GitBook plugin configuration
{
"plugins": [
"advanced-code-blocks",
"code-highlighter",
"copy-code-button",
"tab-groups"
],
"pluginsConfig": {
"advanced-code-blocks": {
"theme": "github",
"lineNumbers": true,
"copyButton": true,
"maxHeight": 400
},
"code-highlighter": {
"themes": [
"github",
"monokai",
"solarized-dark"
],
"autoDetect": true,
"supportedLanguages": [
"javascript",
"python",
"go",
"rust",
"typescript",
"bash",
"sql",
"yaml",
"json"
]
},
"copy-code-button": {
"copyText": "Copy to clipboard",
"copiedText": "Copied!",
"copyError": "Copy failed"
},
"tab-groups": {
"enableScrolling": true,
"theme": "default"
}
}
}
```
Troubleshooting and Best Practices
Common Issues and Solutions
Problem: Code blocks not highlighting properly
Solutions:
<!-- Ensure language specification is correct -->
❌ Incorrect:
```
// JavaScript code but no language specified
function example() {
return "Hello World";
}
```
✅ Correct:
```javascript
// JavaScript code with proper language specification
function example() {
return "Hello World";
}
```
<!-- Check for unsupported language identifiers -->
❌ Problematic:
```js-react
// Non-standard language identifier
const Component = () => <div>Hello</div>;
```
✅ Better:
```jsx
// Standard JSX identifier
const Component = () => <div>Hello</div>;
```
Problem: Line numbers not displaying correctly
Solutions:
/* Ensure proper CSS is loaded */
.highlight .lineno {
display: inline-block !important;
min-width: 2em;
margin-right: 1em;
text-align: right;
color: #666;
}
/* Fix for responsive design */
@media (max-width: 600px) {
.highlight .lineno {
min-width: 1.5em;
font-size: 0.8em;
}
}
Problem: Copy functionality not working
Solutions:
// Enhanced clipboard fallback
async function copyToClipboard(text) {
// Try modern Clipboard API first
if (navigator.clipboard && window.isSecureContext) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch (error) {
console.warn('Clipboard API failed:', error);
}
}
// Fallback for older browsers or insecure contexts
return fallbackCopyTextToClipboard(text);
}
function fallbackCopyTextToClipboard(text) {
const textArea = document.createElement("textarea");
textArea.value = text;
// Avoid scrolling to bottom
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";
textArea.style.opacity = "0";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
const successful = document.execCommand('copy');
document.body.removeChild(textArea);
return successful;
} catch (err) {
console.error('Fallback copy failed:', err);
document.body.removeChild(textArea);
return false;
}
}
Conclusion
Advanced Markdown code highlighting represents a critical component of professional technical documentation that enhances code comprehension, improves learning outcomes, and creates polished presentation standards for programming examples and technical tutorials. By implementing proper syntax specification, custom theme configuration, and interactive enhancement features, technical writers can create compelling documentation that serves developers across different skill levels and accessibility needs.
The key to successful code highlighting lies in understanding both the technical implementation details and the user experience considerations that make code examples truly valuable for readers. Whether you’re building simple tutorials or comprehensive API documentation, the techniques covered in this guide provide the foundation for creating professional-grade code presentation that enhances rather than complicates the content creation process.
Remember to test your highlighting implementation across different browsers and devices, implement proper accessibility features for screen readers and keyboard navigation, and maintain consistency in your code presentation standards throughout your documentation. With proper implementation of advanced code highlighting techniques, your Markdown documentation can achieve the professional polish and technical accuracy that modern developers expect from high-quality technical content.