# Syntax Highlighting: Display Code Snippets

# Syntax Highlighting: Display Code Snippets

## Problem

When displaying code snippets in web applications, plain text is difficult to read and understand. Developers need visual distinction between syntax elements like keywords, strings, functions, and comments to quickly parse code logic. Without syntax highlighting, code becomes a wall of uniform text, reducing readability and learning effectiveness.

## Solution

Syntax highlighting libraries like **Prism** and **highlight.js** automatically parse code and apply CSS classes to different syntax elements. These libraries support hundreds of languages and themes, transforming raw code into visually organized, color-coded snippets that improve comprehension and aesthetics.

---

## Code Implementation

### Using Highlight.js

#### Installation

```bash
npm install highlight.js
```

#### Basic HTML Setup

```html
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
</head>
<body>
  <pre><code class="language-javascript">
function fibonacci(n) {
  if (n <= 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}

const result = fibonacci(10);
console.log(result);
  </code></pre>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
  <script>
    hljs.highlightAll();
  </script>
</body>
</html>
```

#### JavaScript Implementation

```javascript
import hljs from 'highlight.js';
import 'highlight.js/styles/atom-one-dark.css';

// Highlight a specific code block
const codeBlock = document.querySelector('code');
hljs.highlightElement(codeBlock);

// Highlight all code blocks
hljs.highlightAll();

// Programmatic highlighting
const code = `
const greeting = "Hello, World!";
console.log(greeting);
`;

const highlighted = hljs.highlight(code, { language: 'javascript' }).value;
document.getElementById('output').innerHTML = highlighted;
```

### Using Prism

#### Installation

```bash
npm install prismjs
```

#### HTML Setup with Prism

```html
<!DOCTYPE html>
<html>
<head>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet" />
</head>
<body>
  <pre><code class="language-python">
def calculate_average(numbers):
    """Calculate the average of a list of numbers."""
    if not numbers:
        return 0
    return sum(numbers) / len(numbers)

scores = [85, 90, 78, 92]
avg = calculate_average(scores)
print(f"Average: {avg}")
  </code></pre>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-python.min.js"></script>
</body>
</html>
```

#### React Component with Prism

```javascript
import React, { useEffect } from 'react';
import Prism from 'prismjs';
import 'prismjs/themes/prism-tomorrow.css';
import 'prismjs/components/prism-javascript';
import 'prismjs/components/prism-python';

const CodeHighlighter = ({ code, language }) => {
  useEffect(() => {
    Prism.highlightAll();
  }, [code]);

  return (
    <pre>
      <code className={`language-${language}`}>
        {code}
      </code>
    </pre>
  );
};

export default CodeHighlighter;

// Usage
<CodeHighlighter 
  code={`const x = 42;\nconsole.log(x);`}
  language="javascript"
/>
```

#### Advanced Prism Configuration

```javascript
import Prism from 'prismjs';
import 'prismjs/themes/prism-dracula.css';
import 'prismjs/components/prism-javascript';
import 'prismjs/components/prism-jsx';
import 'prismjs/components/prism-typescript';
import 'prismjs/plugins/line-numbers/prism-line-numbers.css';
import 'prismjs/plugins/line-numbers/prism-line-numbers.js';
import 'prismjs/plugins/copy-to-clipboard/prism-copy-to-clipboard.js';

// Configure Prism
Prism.manual = false;

// Highlight code with line numbers
const highlightCode = (code, language) => {
  return Prism.highlight(code, Prism.languages[language], language);
};
```

### Comparison Component

```javascript
import React, { useState } from 'react';
import hljs from 'highlight.js';
import 'highlight.js/styles/atom-one-dark.css';

const CodeComparison = () => {
  const [library, setLibrary] = useState('highlight.js');

  const codeSnippet = `
async function fetchData(url) {
  try {
    const response = await fetch(url);
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error:', error);
  }
}
  `.trim();

  const highlighted = hljs.highlight(codeSnippet, { 
    language: 'javascript' 
  }).value;

  return (
    <div>
      <select value={library} onChange={(e) => setLibrary(e.target.value)}>
        <option value="highlight.js">Highlight.js</option>
        <option value="prism">Prism</option>
      </select>
      
      <pre>
        <code 
          dangerouslySetInnerHTML={{ __html: highlighted }}
          className="language-javascript"
        />
      </pre>
    </div>
  );
};

export default CodeComparison;
```

---

## Tips & Best Practices

### 1. **Choose the Right Library**
- **Highlight.js**: Lighter, auto-detects language, simpler setup
- **Prism**: More extensible, plugin ecosystem, better for complex projects

### 2. **Theme Selection**
```css
/* Popular themes */
/* atom-one-dark, atom-one-light, dracula, nord, solarized-dark */
/* Choose based on your application's color scheme */
```

### 3. **Performance Optimization**
```javascript
// Lazy load language support
import('prismjs/components/prism-rust').then(() => {
  Prism.highlightAll();
});

// Only load needed languages, not all
```

### 4. **Accessibility**
```html
<!-- Always include language specification -->
<pre><code class="language-javascript">
  // Good: explicit language
</code></pre>

<!-- Add ARIA labels for screen readers -->
<pre aria-label="JavaScript code example">
  <code class="language-javascript">...</code>
</pre>
```

### 5. **Copy-to-Clipboard Feature**
```javascript
const copyCode = (elementId) => {
  const codeBlock = document.getElementById(elementId);
  navigator.clipboard.writeText(codeBlock.innerText).then(() => {
    alert('Code copied!');
  });
};
```

### 6. **Line Numbers**
```html
<!-- Prism with line numbers -->
<pre class="line-numbers"><code class="language-javascript">
  // Line numbers automatically added
</code></pre>
```

### 7. **Custom Styling**
```css
/* Override default styles */
code[class*="language-"] {
  font-family: 'Fira Code', monospace;
  font-size: 14px;
  line-height: 1.5;
  border-radius: 4px;
  padding: 12px;
}

.token.keyword { color: #ff79c6; }
.token.string { color: #f1fa8c; }
.token.function { color: #8be9fd; }
```

### 8. **Dynamic Language Detection**
```javascript
const detectLanguage = (code) => {
  return hljs.highlightAuto(code).language;
};
```

### 9. **Server-Side Rendering**
```javascript
// Pre-highlight on server for faster initial render
import hljs from 'highlight.js';

const preHighlightCode = (code, language) => {
  return hljs.highlight(code, { language }).value;
};
```

### 10. **Mobile Responsiveness**
```css
pre {
  overflow-x: auto;
  max-width: 100%;
  -webkit-overflow-scrolling: touch;
}

code {
  font-size: clamp(12px, 2vw, 16px);
}
```

---

## Summary

Both **Highlight.js** and **Prism** excel at syntax highlighting with different strengths. Highlight.js offers simplicity and auto-detection, while Prism provides extensibility and plugins. Choose based on project complexity, performance requirements, and desired features. Implement accessibility features, optimize for mobile, and customize themes to match your application's design system.
