Code Blocks
Display syntax-highlighted code examples in multiple programming languages in your Mordoc documentation.
Code Blocks
Code blocks display formatted source code with syntax highlighting, making technical documentation clear and readable. Mordoc supports code blocks in multiple programming languages.
Inline Code
For short code snippets within sentences, use single backticks:
Use the `npm install` command to install dependencies.Result: Use the npm install command to install dependencies.
When to Use Inline Code
- Variable names:
userName - Function names:
calculateTotal() - File names:
config.json - Command names:
git commit - Short code snippets:
const x = 10
Multi-Line Code Blocks
Create code blocks using triple backticks with an optional language identifier:
```javascript
function greet(name) {
console.log(`Hello, ${name}!`);
}
```Result:
function greet(name) {
console.log(`Hello, ${name}!`);
}Language-Specific Syntax Highlighting
Specify the programming language for appropriate syntax highlighting:
JavaScript
```javascript
const fetchData = async (url) => {
const response = await fetch(url);
return response.json();
};
```const fetchData = async (url) => {
const response = await fetch(url);
return response.json();
};TypeScript
```typescript
interface User {
id: number;
name: string;
email: string;
}
function getUser(id: number): Promise<User> {
return fetch(`/api/users/${id}`).then(res => res.json());
}
```interface User {
id: number;
name: string;
email: string;
}
function getUser(id: number): Promise<User> {
return fetch(`/api/users/${id}`).then(res => res.json());
}Python
```python
def calculate_fibonacci(n):
if n <= 1:
return n
return calculate_fibonacci(n-1) + calculate_fibonacci(n-2)
print(calculate_fibonacci(10))
```def calculate_fibonacci(n):
if n <= 1:
return n
return calculate_fibonacci(n-1) + calculate_fibonacci(n-2)
print(calculate_fibonacci(10))Bash/Shell
```bash
#!/bin/bash
npm install
npm run build
npm run preview
```#!/bin/bash
npm install
npm run build
npm run previewJSON
```json
{
"name": "my-docs",
"version": "1.0.0",
"scripts": {
"dev": "mordoc dev",
"build": "mordoc build"
}
}
```{
"name": "my-docs",
"version": "1.0.0",
"scripts": {
"dev": "mordoc dev",
"build": "mordoc build"
}
}YAML
```yaml
- label: Home
path: /
- label: Getting Started
path: /get-started
children:
- label: Installation
path: /get-started/installation
```- label: Home
path: /
- label: Getting Started
path: /get-started
children:
- label: Installation
path: /get-started/installationHTML
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Documentation</title>
</head>
<body>
<h1>Welcome</h1>
</body>
</html>
```<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Documentation</title>
</head>
<body>
<h1>Welcome</h1>
</body>
</html>CSS
```css
.container {
max-width: 1200px;
margin: 0 auto;
padding: 2rem;
}
.button {
background-color: #3b82f6;
color: white;
padding: 0.5rem 1rem;
border-radius: 0.25rem;
}
```.container {
max-width: 1200px;
margin: 0 auto;
padding: 2rem;
}
.button {
background-color: #3b82f6;
color: white;
padding: 0.5rem 1rem;
border-radius: 0.25rem;
}SQL
```sql
SELECT users.name, orders.total
FROM users
INNER JOIN orders ON users.id = orders.user_id
WHERE orders.status = 'completed'
ORDER BY orders.total DESC
LIMIT 10;
```SELECT users.name, orders.total
FROM users
INNER JOIN orders ON users.id = orders.user_id
WHERE orders.status = 'completed'
ORDER BY orders.total DESC
LIMIT 10;Go
```go
package main
import "fmt"
func main() {
message := "Hello, Mordoc!"
fmt.Println(message)
}
```package main
import "fmt"
func main() {
message := "Hello, Mordoc!"
fmt.Println(message)
}Rust
```rust
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let sum: i32 = numbers.iter().sum();
println!("Sum: {}", sum);
}
```fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let sum: i32 = numbers.iter().sum();
println!("Sum: {}", sum);
}Supported Languages
Mordoc supports syntax highlighting for 100+ programming languages. Common languages include:
| Language | Identifier | Language | Identifier |
|---|---|---|---|
| JavaScript | javascript, js | Python | python, py |
| TypeScript | typescript, ts | Ruby | ruby, rb |
| Bash | bash, sh | Go | go |
| JSON | json | Rust | rust, rs |
| YAML | yaml, yml | Java | java |
| HTML | html | C++ | cpp, c++ |
| CSS | css | C# | csharp, cs |
| PHP | php | Swift | swift |
| SQL | sql | Kotlin | kotlin, kt |
For a complete list, see the Prism.js documentation.
Code Block Without Highlighting
For plain text or unsupported languages, omit the language identifier or use text:
```text
This is plain text without syntax highlighting.
No colors or special formatting applied.
```This is plain text without syntax highlighting.
No colors or special formatting applied.Code Block Best Practices
Meaningful Examples
Good:
```javascript
// Calculate compound interest
const calculateInterest = (principal, rate, years) => {
return principal * Math.pow(1 + rate, years);
};
```Poor:
```javascript
// Code
const x = function(a, b, c) {
return a * Math.pow(1 + b, c);
};
```Complete, Runnable Code
Provide code that users can copy and run:
```python
# Complete example with imports
import requests
def fetch_user(user_id):
response = requests.get(f'https://api.example.com/users/{user_id}')
return response.json()
# Usage
user = fetch_user(123)
print(user['name'])
```Comments for Clarity
Use comments to explain complex code:
```javascript
// Initialize the configuration
const config = {
apiUrl: process.env.API_URL,
timeout: 5000
};
// Fetch data with error handling
async function fetchData(endpoint) {
try {
const response = await fetch(`${config.apiUrl}${endpoint}`);
return await response.json();
} catch (error) {
console.error('Fetch failed:', error);
return null;
}
}
```Context Before Code
Explain what the code does before showing it:
To initialize the Mordoc project, run the following command:
```bash
npx create-mordoc-app my-docs
cd my-docs
npm run dev## Multi-File Examples
Show multiple related files:
```markdown
### Configuration Files
**package.json:**
```json
{
"name": "my-app",
"scripts": {
"dev": "vite"
}
}
```
**vite.config.js:**
```javascript
import { defineConfig } from 'vite';
export default defineConfig({
server: {
port: 3000
}
});
```Command Line Examples
Show commands with output:
```bash
$ npm run build
> mordoc build
✓ Building documentation...
✓ Generating search index...
✓ Build complete in 2.3s
Output: dist/
```Diff/Changes
Show code changes using comments:
```javascript
// Before
function greet(name) {
console.log('Hello ' + name);
}
// After
function greet(name) {
console.log(`Hello ${name}!`);
}
```Code Block Titles
Add context with a title above the code block:
**config/site.json:**
```json
{
"title": "My Documentation",
"baseUrl": "https://docs.example.com"
}
```Escaping Code Blocks in Markdown
To show code block syntax itself (like in this documentation), use four backticks:
````markdown
```javascript
console.log('Hello');
```
````Styling Code Blocks
Customize code block appearance through configuration.
Edit config/styles/main.json:
{
"codeBlocks": {
"theme": "github-dark",
"fontSize": "0.875rem",
"lineHeight": "1.6",
"padding": "1rem",
"borderRadius": "0.375rem",
"showLineNumbers": false
}
}Available Style Properties
| Property | Description | Options |
|---|---|---|
theme | Color scheme | github-dark, github-light, dracula, monokai |
fontSize | Text size | 0.75rem, 0.875rem, 1rem |
lineHeight | Line spacing | 1.4, 1.6, 1.8 |
padding | Internal spacing | CSS size values |
borderRadius | Corner rounding | CSS size values |
showLineNumbers | Display line numbers | true, false |
Common Patterns
Installation Instructions
## Installation
Install Mordoc using npm:
```bash
npm install -g mordoc
```
Or with yarn:
```bash
yarn global add mordoc
```API Examples
## Create a New User
```javascript
const response = await fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'John Doe',
email: 'john@example.com'
})
});
const user = await response.json();
console.log('Created user:', user);
```Configuration Examples
## Site Configuration
Edit your `config/site.json` file:
```json
{
"title": "My Documentation",
"description": "Comprehensive project documentation",
"baseUrl": "https://docs.myproject.com",
"language": "en"
}
```Step-by-Step Code
## Building a Component
1. Create the component file:
```javascript
// components/Button.js
export function Button({ label, onClick }) {
return (
<button onClick={onClick}>
{label}
</button>
);
}
```
2. Import and use it:
```javascript
// App.js
import { Button } from './components/Button';
function App() {
return <Button label="Click Me" onClick={() => alert('Clicked!')} />;
}
```Accessibility
- Always specify the language for syntax highlighting
- Provide text descriptions for complex code examples
- Keep code examples concise and focused
- Consider providing alternative explanations for screen reader users
Screen readers may struggle with code blocks. Provide plain-text explanations of what the code does before or after the block.
Troubleshooting
No Syntax Highlighting
- Verify language identifier is correct and supported
- Check backticks are properly closed
- Ensure no extra spaces before language identifier
Code Not Formatting Correctly
- Verify using triple backticks (not single or double)
- Check for proper line breaks before and after code block
- Ensure consistent indentation within code
Special Characters Display Issues
- Escape special markdown characters if needed
- Use HTML entities for problematic characters
- Consider using different quotes or brackets
Next Steps
- Callouts - Create styled alert and info boxes
- Cards - Build visual card layouts
- Configuration - Customize your documentation

