Code Blocks and Syntax Highlighting Tests
This page tests our syntax highlighting system with various programming languages and code block formats.
JavaScript/TypeScript
// Basic JavaScript function
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(x => x * 2);
console.log(doubled);
// TypeScript with interfaces and generics
interface User {
id: number;
name: string;
email?: string;
}
function processUsers<T extends User>(users: T[]): T[] {
return users.filter(user => user.name.length > 0);
}
const users: User[] = [
{ id: 1, name: "Alice", email: "alice@example.com" },
{ id: 2, name: "Bob" }
];
Python
# Machine learning example
import numpy as np
from sklearn.linear_model import LinearRegression
def gradient_descent(X, y, learning_rate=0.01, epochs=1000):
"""Simple gradient descent implementation"""
m, n = X.shape
theta = np.zeros(n)
for i in range(epochs):
predictions = X.dot(theta)
errors = predictions - y
gradient = (1/m) * X.T.dot(errors)
theta = theta - learning_rate * gradient
if i % 100 == 0:
cost = np.sum(errors**2) / (2*m)
print(f"Epoch {i}, Cost: {cost}")
return theta
# Usage
X = np.random.randn(100, 3)
y = X.dot([1.5, -2.0, 1.0]) + np.random.randn(100) * 0.1
theta = gradient_descent(X, y)
React/JSX
// React component with hooks
import React, { useState, useEffect } from 'react';
const BlogPost = ({ post }) => {
const [isLiked, setIsLiked] = useState(false);
const [likeCount, setLikeCount] = useState(post.likes);
useEffect(() => {
// Simulate API call
fetch(`/api/posts/${post.id}/likes`)
.then(res => res.json())
.then(data => setLikeCount(data.count));
}, [post.id]);
const handleLike = async () => {
setIsLiked(!isLiked);
const newCount = isLiked ? likeCount - 1 : likeCount + 1;
setLikeCount(newCount);
await fetch(`/api/posts/${post.id}/like`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ liked: !isLiked })
});
};
return (
<article className="bg-white rounded-lg shadow-md p-6">
<h2 className="text-2xl font-bold mb-4">{post.title}</h2>
<p className="text-gray-600 mb-4">{post.excerpt}</p>
<button
onClick={handleLike}
className={`flex items-center space-x-2 px-4 py-2 rounded ${
isLiked
? 'bg-red-500 text-white'
: 'bg-gray-200 text-gray-700'
}`}
>
<span>❤️</span>
<span>{likeCount}</span>
</button>
</article>
);
};
export default BlogPost;
CSS
/* Modern CSS with Grid and Flexbox */
.blog-layout {
display: grid;
grid-template-columns: 1fr 3fr 1fr;
grid-template-areas:
"sidebar main aside"
"footer footer footer";
gap: 2rem;
max-width: 1200px;
margin: 0 auto;
}
.main-content {
grid-area: main;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 12px;
padding: 2rem;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}
.code-block {
background: #282c34;
color: #abb2bf;
padding: 1rem;
border-radius: 8px;
font-family: 'Fira Code', monospace;
overflow-x: auto;
}
@media (max-width: 768px) {
.blog-layout {
grid-template-columns: 1fr;
grid-template-areas:
"main"
"sidebar"
"aside"
"footer";
}
}
SQL
-- Complex SQL query with CTEs and window functions
WITH monthly_sales AS (
SELECT
DATE_TRUNC('month', order_date) as month,
customer_id,
SUM(total_amount) as monthly_total,
COUNT(*) as order_count
FROM orders
WHERE order_date >= '2024-01-01'
GROUP BY 1, 2
),
customer_rankings AS (
SELECT
month,
customer_id,
monthly_total,
order_count,
ROW_NUMBER() OVER (PARTITION BY month ORDER BY monthly_total DESC) as rank,
LAG(monthly_total) OVER (PARTITION BY customer_id ORDER BY month) as prev_month_total
FROM monthly_sales
)
SELECT
cr.month,
c.customer_name,
cr.monthly_total,
cr.order_count,
cr.rank,
ROUND(
(cr.monthly_total - cr.prev_month_total) / cr.prev_month_total * 100,
2
) as growth_percentage
FROM customer_rankings cr
JOIN customers c ON cr.customer_id = c.id
WHERE cr.rank <= 10
ORDER BY cr.month DESC, cr.rank ASC;
Bash/Shell
#!/bin/bash
# Deployment script with error handling
set -euo pipefail
DEPLOY_ENV=${1:-staging}
PROJECT_DIR="/var/www/myapp"
BACKUP_DIR="/var/backups/myapp"
log() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}
backup_database() {
log "Creating database backup..."
pg_dump myapp_db > "${BACKUP_DIR}/backup_$(date +%Y%m%d_%H%M%S).sql"
# Keep only last 5 backups
ls -t "${BACKUP_DIR}"/backup_*.sql | tail -n +6 | xargs -r rm
}
deploy() {
log "Starting deployment to ${DEPLOY_ENV}"
# Pull latest code
cd "${PROJECT_DIR}"
git fetch origin
git checkout "deploy/${DEPLOY_ENV}"
git pull origin "deploy/${DEPLOY_ENV}"
# Install dependencies
npm ci --production
# Build application
npm run build
# Run migrations
npm run migrate
# Restart services
sudo systemctl restart nginx
sudo systemctl restart myapp
log "Deployment completed successfully!"
}
# Main execution
if [[ "${DEPLOY_ENV}" == "production" ]]; then
backup_database
fi
deploy
Go
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Created time.Time `json:"created"`
}
type UserService struct {
users map[int]*User
nextID int
}
func NewUserService() *UserService {
return &UserService{
users: make(map[int]*User),
nextID: 1,
}
}
func (us *UserService) CreateUser(ctx context.Context, name, email string) (*User, error) {
user := &User{
ID: us.nextID,
Name: name,
Email: email,
Created: time.Now(),
}
us.users[user.ID] = user
us.nextID++
return user, nil
}
func (us *UserService) GetUser(ctx context.Context, id int) (*User, error) {
user, exists := us.users[id]
if !exists {
return nil, fmt.Errorf("user with id %d not found", id)
}
return user, nil
}
func (us *UserService) HandleCreateUser(w http.ResponseWriter, r *http.Request) {
var req struct {
Name string `json:"name"`
Email string `json:"email"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
user, err := us.CreateUser(r.Context(), req.Name, req.Email)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)
}
func main() {
userService := NewUserService()
r := mux.NewRouter()
r.HandleFunc("/users", userService.HandleCreateUser).Methods("POST")
log.Println("Server starting on :8080")
log.Fatal(http.ListenAndServe(":8080", r))
}
Inline Code
Here's some inline code: npm install, git commit -m "fix", and const x = 42.
You can also have inline code with special characters: $PATH, ~/.bashrc, and <div>.
Code Without Language Specification
This is a plain code block without syntax highlighting.
It should still be formatted as code but without colors.
function example() {
return "no highlighting";
}
Indented Code Blocks (Legacy Markdown)
// This is an indented code block (4 spaces)
function oldStyle() {
console.log("Legacy markdown code block");
return true;
}
Mixed Content Test
Here's a paragraph followed by code:
def hello_world():
print("Hello, World!")
And then more text, then inline code print("inline"), and another block:
console.log("Mixed content test");
Final paragraph to test spacing and layout.