Code Syntax Highlighting Demo

Testing the new code syntax highlighting and copy functionality with multiple programming languages.

Yaswanth Gudivada
June 13, 2026
6 min read
Demo
Code Syntax Highlighting Demo

Code Syntax Highlighting Demo

This post demonstrates the new code syntax highlighting and copy functionality across different programming languages.

JavaScript Example

javascript
// React component with hooks
import React, { useState, useEffect } from "react";

const BlogPost = ({ title, content }) => {
  const [isLoading, setIsLoading] = useState(true);
  const [comments, setComments] = useState([]);

  useEffect(() => {
    fetchComments().then((data) => {
      setComments(data);
      setIsLoading(false);
    });
  }, []);

  const handleLike = async () => {
    try {
      await fetch("/api/like", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ postId: title }),
      });
    } catch (error) {
      console.error("Failed to like post:", error);
    }
  };

  return (
    <article className="blog-post">
      <h1>{title}</h1>
      <div dangerouslySetInnerHTML={{ __html: content }} />
      <button onClick={handleLike}>Like</button>
    </article>
  );
};

export default BlogPost;

Python Example

python
# Data processing with pandas
import pandas as pd
import numpy as np
from typing import List, Dict, Optional

class BlogAnalyzer:
    def __init__(self, data_path: str):
        self.data = pd.read_csv(data_path)
        self.processed_data = None

    def analyze_engagement(self) -> Dict[str, float]:
        """Analyze blog post engagement metrics."""
        metrics = {
            'avg_views': self.data['views'].mean(),
            'avg_likes': self.data['likes'].mean(),
            'avg_comments': self.data['comments'].mean()
        }
        return metrics

    def get_top_posts(self, n: int = 10) -> pd.DataFrame:
        """Get top N posts by engagement score."""
        self.data['engagement_score'] = (
            self.data['likes'] * 0.4 +
            self.data['comments'] * 0.6
        )
        return self.data.nlargest(n, 'engagement_score')

    def filter_by_tags(self, tags: List[str]) -> pd.DataFrame:
        """Filter posts by specific tags."""
        mask = self.data['tags'].apply(
            lambda x: any(tag in x for tag in tags)
        )
        return self.data[mask]

# Usage example
analyzer = BlogAnalyzer('blog_data.csv')
top_posts = analyzer.get_top_posts(5)
print(f"Top 5 posts: {top_posts['title'].tolist()}")

TypeScript Example

typescript
// Type definitions for blog system
interface BlogPost {
  id: string;
  title: string;
  content: string;
  excerpt: string;
  author: Author;
  tags: string[];
  publishedAt: Date;
  featuredImage?: string;
  status: "draft" | "published" | "archived";
}

interface Author {
  id: string;
  name: string;
  email: string;
  avatar?: string;
  bio?: string;
}

interface BlogService {
  getPosts(filters?: PostFilters): Promise<BlogPost[]>;
  getPost(id: string): Promise<BlogPost | null>;
  createPost(post: CreatePostData): Promise<BlogPost>;
  updatePost(id: string, updates: Partial<BlogPost>): Promise<BlogPost>;
  deletePost(id: string): Promise<void>;
}

class BlogServiceImpl implements BlogService {
  constructor(private apiClient: ApiClient) {}

  async getPosts(filters?: PostFilters): Promise<BlogPost[]> {
    const params = new URLSearchParams();
    if (filters?.tag) params.append("tag", filters.tag);
    if (filters?.author) params.append("author", filters.author);

    const response = await this.apiClient.get<BlogPost[]>(`/posts?${params}`);
    return response.data;
  }

  async createPost(postData: CreatePostData): Promise<BlogPost> {
    const response = await this.apiClient.post<BlogPost>("/posts", postData);
    return response.data;
  }
}

CSS Example

css
/* Modern blog styling with CSS Grid and Flexbox */
.blog-container {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 2rem;
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.blog-post {
  background: var(--bg-primary);
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.blog-post:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.code-block {
  position: relative;
  background: var(--code-bg);
  border-radius: 8px;
  overflow: hidden;
  margin: 1.5rem 0;
}

.copy-button {
  position: absolute;
  top: 0.75rem;
  right: 0.75rem;
  background: var(--bg-secondary);
  border: none;
  border-radius: 4px;
  padding: 0.5rem 1rem;
  font-size: 0.875rem;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.code-block:hover .copy-button {
  opacity: 1;
}

/* Dark mode support */
@media (prefers-color-scheme: dark) {
  :root {
    --bg-primary: #1a1a1a;
    --bg-secondary: #2d2d2d;
    --text-primary: #ffffff;
    --text-secondary: #a0a0a0;
    --code-bg: #0d1117;
  }
}

SQL Example

sql
-- Database schema for blog system
CREATE TABLE authors (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(100) NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    avatar_url TEXT,
    bio TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE blog_posts (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    title VARCHAR(255) NOT NULL,
    slug VARCHAR(255) UNIQUE NOT NULL,
    content TEXT NOT NULL,
    excerpt TEXT,
    author_id UUID REFERENCES authors(id) ON DELETE CASCADE,
    featured_image_url TEXT,
    status VARCHAR(20) DEFAULT 'draft' CHECK (status IN ('draft', 'published', 'archived')),
    published_at TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE tags (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(50) UNIQUE NOT NULL,
    color VARCHAR(7) DEFAULT '#3B82F6'
);

CREATE TABLE post_tags (
    post_id UUID REFERENCES blog_posts(id) ON DELETE CASCADE,
    tag_id UUID REFERENCES tags(id) ON DELETE CASCADE,
    PRIMARY KEY (post_id, tag_id)
);

-- Query to get posts with author and tags
SELECT
    bp.id,
    bp.title,
    bp.slug,
    bp.excerpt,
    bp.published_at,
    a.name as author_name,
    a.avatar_url as author_avatar,
    STRING_AGG(t.name, ', ') as tags
FROM blog_posts bp
JOIN authors a ON bp.author_id = a.id
LEFT JOIN post_tags pt ON bp.id = pt.post_id
LEFT JOIN tags t ON pt.tag_id = t.id
WHERE bp.status = 'published'
GROUP BY bp.id, a.name, a.avatar_url
ORDER BY bp.published_at DESC
LIMIT 10;

JSON Example

json
{
  "blog": {
    "title": "My Tech Blog",
    "description": "A blog about web development and technology",
    "author": {
      "name": "John Doe",
      "email": "john@example.com",
      "social": {
        "twitter": "@johndoe",
        "github": "johndoe",
        "linkedin": "johndoe"
      }
    },
    "settings": {
      "theme": "dark",
      "postsPerPage": 10,
      "enableComments": true,
      "enableNewsletter": true
    },
    "navigation": [
      {
        "label": "Home",
        "path": "/",
        "icon": "home"
      },
      {
        "label": "Blog",
        "path": "/blog",
        "icon": "book"
      },
      {
        "label": "About",
        "path": "/about",
        "icon": "user"
      },
      {
        "label": "Contact",
        "path": "/contact",
        "icon": "mail"
      }
    ]
  },
  "posts": [
    {
      "id": "1",
      "title": "Getting Started with React",
      "slug": "getting-started-with-react",
      "excerpt": "Learn the basics of React development",
      "tags": ["react", "javascript", "frontend"],
      "publishedAt": "2024-01-15T10:00:00Z",
      "readTime": "5 min"
    }
  ]
}

Bash Example

bash
#!/bin/bash

# Blog deployment script
set -e

echo "๐Ÿš€ Starting blog deployment..."

# Build the application
echo "๐Ÿ“ฆ Building application..."
npm run build

# Run tests
echo "๐Ÿงช Running tests..."
npm test

# Deploy to production
echo "๐ŸŒ Deploying to production..."
rsync -avz --delete dist/ user@server:/var/www/blog/

# Clear cache
echo "๐Ÿงน Clearing cache..."
ssh user@server "cd /var/www/blog && php artisan cache:clear"

# Restart services
echo "๐Ÿ”„ Restarting services..."
ssh user@server "sudo systemctl restart nginx"
ssh user@server "sudo systemctl restart php8.1-fpm"

echo "โœ… Deployment completed successfully!"

# Send notification
curl -X POST "https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "Blog deployment completed successfully! ๐ŸŽ‰",
    "channel": "#deployments"
  }'

Features Demonstrated

This post showcases the following features:

  1. Syntax Highlighting - Code blocks are highlighted with appropriate colors for each language
  2. Copy Functionality - Each code block has a copy button that appears on hover
  3. Language Detection - The system automatically detects the programming language
  4. Dark Mode Support - Code blocks adapt to the current theme
  5. Responsive Design - Code blocks are responsive and scrollable on mobile devices

Try hovering over any code block above to see the copy button in action! ๐ŸŽฏ