Code Syntax Highlighting Showcase

This post demonstrates syntax highlighting for various programming languages. It's a great way to test how different code snippets look on the blog.

Python

Python is known for its clean syntax and readability:

from typing import List, Optional
 
class TreeNode:
    def __init__(self, val: int = 0):
        self.val = val
        self.left = None
        self.right = None
 
def depth_first_search(root: Optional[TreeNode]) -> List[int]:
    """
    Performs a depth-first search on a binary tree.
    Returns a list of node values in pre-order traversal.
    """
    if not root:
        return []
    
    result = []
    stack = [root]
    
    while stack:
        node = stack.pop()
        result.append(node.val)
        
        if node.right:
            stack.append(node.right)
        if node.left:
            stack.append(node.left)
    
    return result

Go

Go is known for its simplicity and powerful concurrency features:

package main
 
import (
    "fmt"
    "sync"
    "time"
)
 
func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
    defer wg.Done()
    
    for j := range jobs {
        fmt.Printf("worker %d started job %d\n", id, j)
        time.Sleep(time.Second)
        fmt.Printf("worker %d finished job %d\n", id, j)
        results <- j * 2
    }
}
 
func main() {
    jobs := make(chan int, 5)
    results := make(chan int, 5)
    var wg sync.WaitGroup
 
    // Start 3 workers
    for w := 1; w <= 3; w++ {
        wg.Add(1)
        go worker(w, jobs, results, &wg)
    }
 
    // Send 5 jobs
    for j := 1; j <= 5; j++ {
        jobs <- j
    }
    close(jobs)
 
    // Wait for all workers to complete
    wg.Wait()
    close(results)
 
    // Collect results
    for r := range results {
        fmt.Println("Result:", r)
    }
}

CSS

CSS with modern features and responsive design:

/* Modern CSS with custom properties and media queries */
:root {
  --primary-color: #2563eb;
  --secondary-color: #3b82f6;
  --text-color: #1f2937;
  --spacing-unit: 1rem;
}
 
.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: var(--spacing-unit);
  padding: calc(var(--spacing-unit) * 2);
}
 
.card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
  transition: transform 0.2s ease;
}
 
.card:hover {
  transform: translateY(-2px);
}
 
@media (prefers-color-scheme: dark) {
  :root {
    --text-color: #f3f4f6;
  }
 
  .card {
    background: #1f2937;
  }
}
 
@media (max-width: 768px) {
  .container {
    grid-template-columns: 1fr;
    padding: var(--spacing-unit);
  }
}

JavaScript/TypeScript

Modern JavaScript with TypeScript types:

interface User {
  id: string;
  name: string;
  email: string;
  preferences?: {
    theme: 'light' | 'dark';
    notifications: boolean;
  };
}
 
class UserService {
  private users: Map<string, User>;
 
  constructor() {
    this.users = new Map();
  }
 
  async createUser(userData: Omit<User, 'id'>): Promise<User> {
    const id = crypto.randomUUID();
    const user: User = {
      id,
      ...userData,
      preferences: {
        theme: 'light',
        notifications: true,
        ...userData.preferences,
      },
    };
 
    this.users.set(id, user);
    return user;
  }
 
  async getUser(id: string): Promise<User | undefined> {
    return this.users.get(id);
  }
}
 
// Usage example
const userService = new UserService();
 
(async () => {
  try {
    const user = await userService.createUser({
      name: 'John Doe',
      email: 'john@example.com',
      preferences: { theme: 'dark', notifications: false },
    });
    console.log('Created user:', user);
  } catch (error) {
    console.error('Error creating user:', error);
  }
})();

SQL

SQL queries with different operations:

-- Create a table with modern features
CREATE TABLE products (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(255) NOT NULL,
    description TEXT,
    price DECIMAL(10, 2) NOT NULL,
    category_id INTEGER REFERENCES categories(id),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
 
-- Complex query with joins and window functions
SELECT 
    p.name,
    p.price,
    c.name as category,
    AVG(p.price) OVER (PARTITION BY c.id) as avg_category_price,
    RANK() OVER (PARTITION BY c.id ORDER BY p.price DESC) as price_rank
FROM products p
JOIN categories c ON p.category_id = c.id
WHERE p.price > 100
    AND p.created_at >= NOW() - INTERVAL '30 days'
GROUP BY p.id, c.id
HAVING COUNT(*) > 1
ORDER BY c.name, p.price DESC;

Ruby

Ruby with its elegant syntax:

# A module for handling authentication
module Authentication
  extend ActiveSupport::Concern
 
  included do
    before_action :authenticate_user!
    helper_method :current_user
  end
 
  class_methods do
    def require_admin
      before_action :verify_admin
    end
  end
 
  def authenticate_user!
    unless current_user
      flash[:alert] = "Please sign in to continue"
      redirect_to login_path
    end
  end
 
  def current_user
    @current_user ||= User.find_by(id: session[:user_id])
  end
 
  private
 
  def verify_admin
    unless current_user&.admin?
      flash[:error] = "Access denied"
      redirect_to root_path
    end
  end
end
 
# Using the module in a controller
class AdminController < ApplicationController
  include Authentication
  require_admin
 
  def dashboard
    @stats = {
      users: User.count,
      posts: Post.count,
      comments: Comment.count
    }
  end
end

This post showcases syntax highlighting for various programming languages. Each example demonstrates real-world code patterns and best practices. The syntax highlighting should make it easy to distinguish different code elements like:

  • Keywords and control structures
  • Strings and numbers
  • Comments and documentation
  • Function and variable names
  • Types and annotations
  • Special syntax elements

Feel free to use these examples to test syntax highlighting in your own projects!