Code Snippets Guide - nself-org/nchat GitHub Wiki
Complete guide to using code snippets and syntax highlighting in nself-chat.
The code highlighting system provides:
- Inline Code: Backtick syntax for inline code snippets
- Code Blocks: Triple backtick syntax with 100+ language support
- Syntax Highlighting: Using lowlight (highlight.js) for accurate highlighting
- Interactive Features: Copy, download, expand/collapse, line numbers
- Code Snippet Modal: Create and share formatted code snippets
- Theme Support: Automatic light/dark mode switching
Location: /src/components/chat/InlineCode.tsx
Renders inline code with monospace font and background highlighting.
import { InlineCode } from '@/components/chat/InlineCode'
;<InlineCode>const greeting = "Hello"</InlineCode>Features:
- Monospace font
- Background highlight
- Click to copy
- Theme-aware colors
Location: /src/components/chat/CodeBlock.tsx
Full-featured code block with syntax highlighting.
import { CodeBlock } from '@/components/chat/CodeBlock'
;<CodeBlock
code={sourceCode}
language="typescript"
filename="example.ts"
showLineNumbers={true}
maxHeight={500}
/>Props:
| Prop | Type | Default | Description |
|---|---|---|---|
code |
string |
required | Source code to highlight |
language |
string |
auto-detect | Programming language |
filename |
string |
undefined | Display filename in header |
showLineNumbers |
boolean |
true |
Show line numbers |
maxHeight |
number |
500 |
Max height in pixels |
onExpand |
function |
undefined | Callback for expand button |
Features:
- Syntax highlighting for 100+ languages
- Line numbers with hover effects
- Copy button with success feedback
- Download button (saves as file)
- Expand/collapse for long code (>20 lines)
- Language badge
- Auto-detect language from filename or content
Location: /src/components/chat/CodeSnippetModal.tsx
Modal for creating and sharing code snippets.
import { CodeSnippetModal } from '@/components/chat/CodeSnippetModal'
const [open, setOpen] = useState(false)
const handleShare = async (snippet: CodeSnippet) => {
// Send snippet to backend
await sendMessage({
type: 'code',
...snippet,
})
}
;<CodeSnippetModal
open={open}
onOpenChange={setOpen}
onShare={handleShare}
defaultLanguage="javascript"
/>Features:
- Title and description fields
- Language selector (100+ languages, grouped by category)
- TipTap code editor with syntax highlighting
- Live preview tab
- Keyboard shortcuts (Cmd/Ctrl+Enter to share)
The system supports 100+ languages including:
- JavaScript (js, jsx)
- TypeScript (ts, tsx)
- HTML/XML
- CSS, SCSS, LESS
- Vue, Svelte
- Python (py)
- Java
- Go (golang)
- Rust (rs)
- Ruby (rb)
- PHP
- C/C++
- C# (cs)
- Bash (sh, shell, zsh)
- PowerShell (ps1)
- JSON
- YAML (yml)
- TOML
- XML
- SQL
- PostgreSQL (pgsql)
- MongoDB
- Markdown (md)
- Diff/Patch
- Dockerfile
- GraphQL (gql)
- Makefile
- Assembly (asm, nasm)
Full list: See getSupportedLanguages() in /src/lib/markdown/syntax-highlighter.ts
Location: /src/lib/markdown/syntax-highlighter.ts
Core utility functions for syntax highlighting.
Highlight code with syntax highlighting.
import { highlightCode } from '@/lib/markdown/syntax-highlighter'
const { html, language } = highlightCode('const x = 42', 'javascript')
// html: highlighted HTML string
// language: detected or provided languageAuto-detect language from filename or content.
import { detectLanguage } from '@/lib/markdown/syntax-highlighter'
const lang = detectLanguage('example.py')
// Returns: 'python'
const lang2 = detectLanguage(undefined, '<?php echo "Hello"; ?>')
// Returns: 'php'Get list of all supported languages.
import { getSupportedLanguages } from '@/lib/markdown/syntax-highlighter'
const languages = getSupportedLanguages()
// Returns: Array of LanguageInfo objectsGet human-readable language name.
import { getLanguageDisplayName } from '@/lib/markdown/syntax-highlighter'
const display = getLanguageDisplayName('js')
// Returns: 'JavaScript'Users can write code in messages using markdown syntax:
Inline code:
Use `const x = 42` for constants.
Code blocks:
```javascript
function greet(name) {
return `Hello, ${name}!`
}
```
With filename:
```typescript:src/utils/helper.ts
export function helper() {
// implementation
}
```
The MessageContent component automatically parses and renders code:
import { MessageContent } from '@/components/chat/message-content'
;<MessageContent content={message.content} type="text" />Code blocks in the content will be automatically:
- Detected (triple backticks)
- Language identified
- Syntax highlighted
- Rendered with full features
Location: /src/styles/syntax-highlighting.css
The system includes comprehensive syntax highlighting styles:
- Light mode colors (GitHub Light theme)
- Dark mode colors (GitHub Dark theme)
- Smooth transitions
- Hover effects
- Scrollbar styling
- Print-friendly styles
The highlighting automatically adapts to:
- System theme preference
- App theme setting
- Dark/light mode toggle
To customize colors, edit /src/styles/syntax-highlighting.css:
/* Example: Custom keyword color in dark mode */
.dark .hljs-keyword {
color: #your-color !important;
}See /src/components/chat/code-snippets-example.tsx for comprehensive examples:
- Inline code examples
- Code blocks with various languages
- Code snippet modal usage
- Message with embedded code
# Add to your app
import { CodeSnippetsExample } from '@/components/chat/code-snippets-example'
<CodeSnippetsExample />-
Always specify language for better highlighting:
```typescript // Good - language specified ``` -
Use descriptive filenames when sharing snippets
-
Keep code blocks focused - break large files into logical sections
-
Add comments to explain complex logic
-
Lazy load languages - Only register languages as needed
-
Sanitize code - Always sanitize before rendering HTML
-
Limit code length - Show collapse UI for long snippets
-
Provide fallbacks - Handle unsupported languages gracefully
-
Test accessibility - Ensure keyboard navigation works
-
Memoize highlighted code:
const highlightedCode = useMemo(() => highlightCode(code, language), [code, language])
-
Virtual scrolling for long code blocks:
import { useVirtualizer } from '@tanstack/react-virtual'
-
Code splitting:
const CodeBlock = lazy(() => import('./CodeBlock'))
The code highlighting system is fully accessible:
- Keyboard navigation: All buttons are keyboard accessible
- Screen readers: Proper ARIA labels and semantic HTML
- Focus indicators: Visible focus rings on all interactive elements
- Color contrast: WCAG AA compliant colors
-
Reduced motion: Respects
prefers-reduced-motion
interface CodeBlockProps {
code: string // Source code (required)
language?: string // Language identifier
filename?: string // Display filename
showLineNumbers?: boolean // Show line numbers (default: true)
maxHeight?: number // Max height in pixels (default: 500)
className?: string // Additional CSS classes
onExpand?: () => void // Callback for expand button
}interface CodeSnippet {
title: string // Snippet title
language: string // Programming language
code: string // Source code
description?: string // Optional description
}interface LanguageInfo {
name: string // Canonical name (e.g., 'javascript')
aliases: string[] // Alternative names (e.g., ['js', 'jsx'])
displayName: string // Display name (e.g., 'JavaScript')
extension: string // File extension (e.g., '.js')
category: string // Category (e.g., 'Web', 'Backend')
}Solution: Check if language is supported:
import { isLanguageSupported } from '@/lib/markdown/syntax-highlighter'
if (!isLanguageSupported('mylang')) {
console.log('Language not supported')
}Solution: Clear browser cache and ensure CSS is loaded:
# Rebuild CSS
pnpm buildSolution: Check clipboard permissions:
// Modern browsers require HTTPS or localhost
navigator.clipboard.writeText(code)Solution: Use maxHeight and collapse features:
<CodeBlock
code={largeCode}
maxHeight={300}
// Will auto-collapse if >20 lines
/>Planned features:
- Monaco editor integration for full IDE experience
- AI-powered code suggestions
- Diff view for code changes
- Code execution in sandbox
- Collaborative code editing
- Code snippet search
- Syntax error detection
- Auto-formatting on paste
- lowlight - Syntax highlighter
- highlight.js - Language definitions
- TipTap - Rich text editor
- Radix UI - UI primitives
For issues or questions:
- Check this guide
- Review
/src/components/chat/code-snippets-example.tsx - Open an issue on GitHub
- Contact the development team
Version: 1.0.0 Last Updated: February 1, 2026 Maintainer: nself-chat team