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:

Markdown
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:

Markdown
```javascript
function greet(name) {
  console.log(`Hello, ${name}!`);
}
```

Result:

Javascript
function greet(name) {
  console.log(`Hello, ${name}!`);
}

Language-Specific Syntax Highlighting

Specify the programming language for appropriate syntax highlighting:

JavaScript

Markdown
```javascript
const fetchData = async (url) => {
  const response = await fetch(url);
  return response.json();
};
```
Javascript
const fetchData = async (url) => {
  const response = await fetch(url);
  return response.json();
};

TypeScript

Markdown
```typescript
interface User {
  id: number;
  name: string;
  email: string;
}

function getUser(id: number): Promise<User> {
  return fetch(`/api/users/${id}`).then(res => res.json());
}
```
Typescript
interface User {
  id: number;
  name: string;
  email: string;
}

function getUser(id: number): Promise<User> {
  return fetch(`/api/users/${id}`).then(res => res.json());
}

Python

Markdown
```python
def calculate_fibonacci(n):
    if n <= 1:
        return n
    return calculate_fibonacci(n-1) + calculate_fibonacci(n-2)

print(calculate_fibonacci(10))
```
Python
def calculate_fibonacci(n):
    if n <= 1:
        return n
    return calculate_fibonacci(n-1) + calculate_fibonacci(n-2)

print(calculate_fibonacci(10))

Bash/Shell

Markdown
```bash
#!/bin/bash
npm install
npm run build
npm run preview
```
Bash
#!/bin/bash
npm install
npm run build
npm run preview

JSON

Markdown
```json
{
  "name": "my-docs",
  "version": "1.0.0",
  "scripts": {
    "dev": "mordoc dev",
    "build": "mordoc build"
  }
}
```
Json
{
  "name": "my-docs",
  "version": "1.0.0",
  "scripts": {
    "dev": "mordoc dev",
    "build": "mordoc build"
  }
}

YAML

Markdown
```yaml
- label: Home
  path: /
- label: Getting Started
  path: /get-started
  children:
    - label: Installation
      path: /get-started/installation
```
Yaml
- label: Home
  path: /
- label: Getting Started
  path: /get-started
  children:
    - label: Installation
      path: /get-started/installation

HTML

Markdown
```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My Documentation</title>
</head>
<body>
  <h1>Welcome</h1>
</body>
</html>
```
HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My Documentation</title>
</head>
<body>
  <h1>Welcome</h1>
</body>
</html>

CSS

Markdown
```css
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.button {
  background-color: #3b82f6;
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 0.25rem;
}
```
Css
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.button {
  background-color: #3b82f6;
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 0.25rem;
}

SQL

Markdown
```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;
```
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;

Go

Markdown
```go
package main

import "fmt"

func main() {
    message := "Hello, Mordoc!"
    fmt.Println(message)
}
```
Go
package main

import "fmt"

func main() {
    message := "Hello, Mordoc!"
    fmt.Println(message)
}

Rust

Markdown
```rust
fn main() {
    let numbers = vec![1, 2, 3, 4, 5];
    let sum: i32 = numbers.iter().sum();
    println!("Sum: {}", sum);
}
```
Rust
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:

LanguageIdentifierLanguageIdentifier
JavaScriptjavascript, jsPythonpython, py
TypeScripttypescript, tsRubyruby, rb
Bashbash, shGogo
JSONjsonRustrust, rs
YAMLyaml, ymlJavajava
HTMLhtmlC++cpp, c++
CSScssC#csharp, cs
PHPphpSwiftswift
SQLsqlKotlinkotlin, 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:

Markdown
```text
This is plain text without syntax highlighting.
No colors or special formatting applied.
```
Text
This is plain text without syntax highlighting.
No colors or special formatting applied.

Code Block Best Practices

Meaningful Examples

Good:

Markdown
```javascript
// Calculate compound interest
const calculateInterest = (principal, rate, years) => {
  return principal * Math.pow(1 + rate, years);
};
```

Poor:

Markdown
```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:

Markdown
```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:

Markdown
```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:

Markdown
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:

Markdown
```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:

Markdown
```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:

Markdown
**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
````markdown
```javascript
console.log('Hello');
```
````

Styling Code Blocks

Customize code block appearance through configuration.

Edit config/styles/main.json:

Json
{
  "codeBlocks": {
    "theme": "github-dark",
    "fontSize": "0.875rem",
    "lineHeight": "1.6",
    "padding": "1rem",
    "borderRadius": "0.375rem",
    "showLineNumbers": false
  }
}

Available Style Properties

PropertyDescriptionOptions
themeColor schemegithub-dark, github-light, dracula, monokai
fontSizeText size0.75rem, 0.875rem, 1rem
lineHeightLine spacing1.4, 1.6, 1.8
paddingInternal spacingCSS size values
borderRadiusCorner roundingCSS size values
showLineNumbersDisplay line numberstrue, false

Common Patterns

Installation Instructions

Markdown
## Installation

Install Mordoc using npm:

```bash
npm install -g mordoc
```

Or with yarn:

```bash
yarn global add mordoc
```

API Examples

Markdown
## 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

Markdown
## 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

Markdown
## 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
Code Accessibility

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