Skip to content

囲み付きコードブロック ​

囲み付きコードブロックは、Markdownの拡張構文の重要な機能で、基本的なコードブロックよりも強力なコード表示機能を提供し、構文強調表示、行番号、ファイル名、その他の高度な機能を含みます。

基本的な囲み付きコードブロック ​

3つのバッククォート ​

3つのバッククォート ``` を使用してコードブロックを作成します:

markdown
```
function hello() {
    console.log("Hello, World!");
}
```

レンダリング結果:

function hello() {
    console.log("Hello, World!");
}

3つのチルダ ​

3つのチルダ ~~~ を使用してコードブロックを作成することもできます:

markdown
~~~
function hello() {
    console.log("Hello, World!");
}
~~~

レンダリング結果:

function hello() {
    console.log("Hello, World!");
}

構文強調表示 ​

プログラミング言語の指定 ​

開始マーカーの後に言語名を指定して、構文強調表示を有効にします:

markdown
```javascript
function fibonacci(n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

console.log(fibonacci(10)); // 55
```

レンダリング結果:

javascript
function fibonacci(n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

console.log(fibonacci(10)); // 55

一般的な言語例 ​

Python ​

markdown
```python
def quicksort(arr):
    if len(arr) <= 1:
        return arr
    
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    
    return quicksort(left) + middle + quicksort(right)

# 例
numbers = [3, 6, 8, 10, 1, 2, 1]
print(quicksort(numbers))
```

レンダリング結果:

python
def quicksort(arr):
    if len(arr) <= 1:
        return arr
    
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    
    return quicksort(left) + middle + quicksort(right)

# 例
numbers = [3, 6, 8, 10, 1, 2, 1]
print(quicksort(numbers))

TypeScript ​

markdown
```typescript
interface User {
    id: number;
    name: string;
    email: string;
    isActive: boolean;
}

class UserService {
    private users: User[] = [];

    async createUser(userData: Omit<User, 'id'>): Promise<User> {
        const newUser: User = {
            id: Date.now(),
            ...userData
        };
        
        this.users.push(newUser);
        return newUser;
    }

    async getUserById(id: number): Promise<User | undefined> {
        return this.users.find(user => user.id === id);
    }
}
```

レンダリング結果:

typescript
interface User {
    id: number;
    name: string;
    email: string;
    isActive: boolean;
}

class UserService {
    private users: User[] = [];

    async createUser(userData: Omit<User, 'id'>): Promise<User> {
        const newUser: User = {
            id: Date.now(),
            ...userData
        };
        
        this.users.push(newUser);
        return newUser;
    }

    async getUserById(id: number): Promise<User | undefined> {
        return this.users.find(user => user.id === id);
    }
}

Go ​

markdown
```go
package main

import (
    "fmt"
    "net/http"
    "log"
)

type Server struct {
    port string
}

func NewServer(port string) *Server {
    return &Server{port: port}
}

func (s *Server) Start() error {
    http.HandleFunc("/", s.handleHome)
    http.HandleFunc("/api/health", s.handleHealth)
    
    fmt.Printf("サーバーがポート %s で起動中...\n", s.port)
    return http.ListenAndServe(":"+s.port, nil)
}

func (s *Server) handleHome(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Go サーバーへようこそ!")
}

func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    fmt.Fprintf(w, `{"status": "healthy"}`)
}

func main() {
    server := NewServer("8080")
    log.Fatal(server.Start())
}
```

レンダリング結果:

go
package main

import (
    "fmt"
    "net/http"
    "log"
)

type Server struct {
    port string
}

func NewServer(port string) *Server {
    return &Server{port: port}
}

func (s *Server) Start() error {
    http.HandleFunc("/", s.handleHome)
    http.HandleFunc("/api/health", s.handleHealth)
    
    fmt.Printf("サーバーがポート %s で起動中...\n", s.port)
    return http.ListenAndServe(":"+s.port, nil)
}

func (s *Server) handleHome(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Go サーバーへようこそ!")
}

func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    fmt.Fprintf(w, `{"status": "healthy"}`)
}

func main() {
    server := NewServer("8080")
    log.Fatal(server.Start())
}

高度な機能 ​

行の強調表示 ​

一部のMarkdownプロセッサは特定の行を強調表示します:

markdown
```javascript {2,4-6}
function calculateTotal(items) {
    let total = 0; // この行が強調表示されます
    
    for (const item of items) { // これらの行が強調表示されます
        total += item.price * item.quantity;
    } // 強調表示終了
    
    return total;
}
```

行番号の表示 ​

コード行番号を表示します:

markdown
```python:line-numbers
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    
    return -1
```

ファイル名タイトル ​

コードファイル名を表示します:

markdown
```typescript title="userService.ts"
export class UserService {
    private apiUrl = '/api/users';

    async getUsers(): Promise<User[]> {
        const response = await fetch(this.apiUrl);
        return response.json();
    }

    async createUser(user: CreateUserDto): Promise<User> {
        const response = await fetch(this.apiUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(user)
        });
        return response.json();
    }
}
```

コードブロック差分表示 ​

コードの変更を表示します:

markdown
```diff
function calculateTax(amount) {
-   return amount * 0.05; // 古い税率
+   return amount * 0.08; // 新しい税率
}

+ // 新しい関数
+ function calculateDiscount(amount, percentage) {
+     return amount * (percentage / 100);
+ }
```

レンダリング結果:

diff
function calculateTax(amount) {
-   return amount * 0.05; // 古い税率
+   return amount * 0.08; // 新しい税率
}

+ // 新しい関数
+ function calculateDiscount(amount, percentage) {
+     return amount * (percentage / 100);
+ }

設定ファイルの例 ​

JSON設定 ​

markdown
```json
{
  "name": "my-app",
  "version": "1.0.0",
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js",
    "build": "webpack --mode production",
    "test": "jest"
  },
  "dependencies": {
    "express": "^4.18.2",
    "mongoose": "^7.0.3",
    "jsonwebtoken": "^9.0.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.22",
    "jest": "^29.5.0",
    "webpack": "^5.82.0"
  }
}
```

レンダリング結果:

json
{
  "name": "my-app",
  "version": "1.0.0",
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js",
    "build": "webpack --mode production",
    "test": "jest"
  },
  "dependencies": {
    "express": "^4.18.2",
    "mongoose": "^7.0.3",
    "jsonwebtoken": "^9.0.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.22",
    "jest": "^29.5.0",
    "webpack": "^5.82.0"
  }
}

YAML設定 ​

markdown
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-app
  labels:
    app: web-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web-app
  template:
    metadata:
      labels:
        app: web-app
    spec:
      containers:
      - name: web
        image: nginx:1.21
        ports:
        - containerPort: 80
        env:
        - name: NODE_ENV
          value: production
        resources:
          requests:
            memory: "64Mi"
            cpu: "250m"
          limits:
            memory: "128Mi"
            cpu: "500m"
```

レンダリング結果:

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-app
  labels:
    app: web-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web-app
  template:
    metadata:
      labels:
        app: web-app
    spec:
      containers:
      - name: web
        image: nginx:1.21
        ports:
        - containerPort: 80
        env:
        - name: NODE_ENV
          value: production
        resources:
          requests:
            memory: "64Mi"
            cpu: "250m"
          limits:
            memory: "128Mi"
            cpu: "500m"

SQLクエリ ​

markdown
```sql
-- Create users table
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Create indexes
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_username ON users(username);

-- Query active users
SELECT 
    u.id,
    u.username,
    u.email,
    COUNT(p.id) as post_count
FROM users u
LEFT JOIN posts p ON u.id = p.user_id
WHERE u.created_at >= NOW() - INTERVAL '30 days'
GROUP BY u.id, u.username, u.email
HAVING COUNT(p.id) > 0
ORDER BY post_count DESC
LIMIT 10;
```

レンダリング結果:

sql
-- Create users table
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Create indexes
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_username ON users(username);

-- Query active users
SELECT 
    u.id,
    u.username,
    u.email,
    COUNT(p.id) as post_count
FROM users u
LEFT JOIN posts p ON u.id = p.user_id
WHERE u.created_at >= NOW() - INTERVAL '30 days'
GROUP BY u.id, u.username, u.email
HAVING COUNT(p.id) > 0
ORDER BY post_count DESC
LIMIT 10;

シェルスクリプトとコマンド ​

Bashスクリプト ​

markdown
```bash
#!/bin/bash

# Deployment script
set -e

APP_NAME="my-app"
DEPLOY_DIR="/var/www/${APP_NAME}"
BACKUP_DIR="/var/backups/${APP_NAME}"
CURRENT_DATE=$(date +%Y%m%d_%H%M%S)

echo "Starting deployment of ${APP_NAME}..."

# Create backup
if [ -d "$DEPLOY_DIR" ]; then
    echo "Creating backup at ${BACKUP_DIR}/${CURRENT_DATE}"
    mkdir -p "$BACKUP_DIR"
    cp -r "$DEPLOY_DIR" "${BACKUP_DIR}/${CURRENT_DATE}"
fi

# Stop service
echo "Stopping service..."
sudo systemctl stop $APP_NAME || true

# Deploy new version
echo "Deploying new version..."
rm -rf "$DEPLOY_DIR"
mkdir -p "$DEPLOY_DIR"
tar -xzf "${APP_NAME}.tar.gz" -C "$DEPLOY_DIR"

# Install dependencies
echo "Installing dependencies..."
cd "$DEPLOY_DIR"
npm ci --production

# Start service
echo "Starting service..."
sudo systemctl start $APP_NAME
sudo systemctl enable $APP_NAME

echo "Deployment complete!"
```

レンダリング結果:

bash
#!/bin/bash

# Deployment script
set -e

APP_NAME="my-app"
DEPLOY_DIR="/var/www/${APP_NAME}"
BACKUP_DIR="/var/backups/${APP_NAME}"
CURRENT_DATE=$(date +%Y%m%d_%H%M%S)

echo "Starting deployment of ${APP_NAME}..."

# Create backup
if [ -d "$DEPLOY_DIR" ]; then
    echo "Creating backup at ${BACKUP_DIR}/${CURRENT_DATE}"
    mkdir -p "$BACKUP_DIR"
    cp -r "$DEPLOY_DIR" "${BACKUP_DIR}/${CURRENT_DATE}"
fi

# Stop service
echo "Stopping service..."
sudo systemctl stop $APP_NAME || true

# Deploy new version
echo "Deploying new version..."
rm -rf "$DEPLOY_DIR"
mkdir -p "$DEPLOY_DIR"
tar -xzf "${APP_NAME}.tar.gz" -C "$DEPLOY_DIR"

# Install dependencies
echo "Installing dependencies..."
cd "$DEPLOY_DIR"
npm ci --production

# Start service
echo "Starting service..."
sudo systemctl start $APP_NAME
sudo systemctl enable $APP_NAME

echo "Deployment complete!"

一般的なエラーと解決策 ​

1. バッククォートの数が一致しない ​

markdown
❌ エラー:
```javascript
function hello() {
    console.log("Hello");
}
``  ← 2つのバッククォート

✅ 正しい:
```javascript
function hello() {
    console.log("Hello");
}
```  ← 3つのバッククォート

2. 言語識別子が不正 ​

markdown
❌ エラー:
```js  ← 一部のプロセッサは認識しません
function hello() {}
```

✅ 推奨:
```javascript  ← 完全な名前を使用
function hello() {}
```

3. 入れ子のコードブロック ​

markdown
❌ 問題: ``` を含むコードを表示できません

✅ 解決:4つのバッククォートで3つのバッククォートを囲みます
````markdown
```javascript
console.log("hello");
```

### 4. 特殊文字の扱い

````markdown
```markdown
<!-- Markdown構文をMarkdownコードブロック内で表示 -->
\`\`\`javascript  ← バッククォートをエスケープ
code here
\`\`\`
```

サポートされる言語リスト ​

プログラミング言語 ​

言語識別子別名
JavaScriptjavascriptjs
TypeScripttypescriptts
Pythonpythonpy
Javajava
C++cppc++, cxx
C#csharpcs
Gogogolang
Rustrustrs
PHPphp
Rubyrubyrb
Swiftswift
Kotlinkotlinkt

マークアップと設定言語 ​

言語識別子用途
HTMLhtmlWebマークアップ
CSScssスタイルシート
XMLxmlデータ交換
JSONjsonデータ形式
YAMLyaml, yml設定ファイル
TOMLtoml設定ファイル
Markdownmarkdown, mdドキュメント

データとクエリ言語 ​

言語識別子用途
SQLsqlデータベースクエリ
GraphQLgraphqlAPIクエリ
Rr統計計算
MATLABmatlab数値計算

シェルとスクリプト ​

言語識別子用途
Bashbash, shUnixシェル
PowerShellpowershell, ps1Windowsシェル
Batchbatch, batWindowsバッチ
Dockerfiledockerfileコンテナ設定

ベストプラクティス ​

1. 適切な言語識別子を選択 ​

markdown
✅ 推奨:正確な言語識別子を使用
```typescript
interface User {
    id: number;
    name: string;
}
```

❌ 推奨しない:間違った識別子を使用
```javascript  ← これはTypeScriptコードです
interface User {
    id: number;
    name: string;
}
```

2. 意味のあるコメントを追加 ​

markdown
✅ 推奨:説明コメントを含める
```python
def fibonacci(n):
    """Calculate the nth Fibonacci number"""
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)
```

❌ 推奨しない:説明なしのコード
```python
def fib(n):
    if n <= 1:
        return n
    return fib(n-1) + fib(n-2)
```

3. コードを簡潔に保つ ​

markdown
✅ 推奨:核心ロジックを表示
```javascript
// ユーザー認証ミドルウェア
function authenticate(req, res, next) {
    const token = req.headers.authorization;
    if (!token) {
        return res.status(401).json({ error: 'No token provided' });
    }
    // 検証ロジック...
    next();
}
```

❌ 推奨しない:関連のないコードを多く含む
```javascript
// 関連のないコードを省略...
```

4. ファイル名タイトルを使用 ​

markdown
✅ 推奨:ファイル名を表示
```javascript title="middleware/auth.js"
export function authenticate(req, res, next) {
    // 認証ロジック
}
```

✅ 推奨:設定ファイル名を表示
```json title="package.json"
{
  "name": "my-app",
  "version": "1.0.0"
}
```

実践的な応用例 ​

1. APIドキュメント ​

markdown
## ユーザーログインAPI

**リクエスト例:**

```bash
curl -X POST https://api.example.com/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "password123"
  }'
```

**レスポンス例:**

```json
{
  "success": true,
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "user": {
      "id": 1,
      "email": "user@example.com",
      "name": "Zhang San"
    }
  }
}
```

**エラーレスポンス:**

```json
{
  "success": false,
  "error": {
    "code": "INVALID_CREDENTIALS",
    "message": "Invalid email or password"
  }
}
```

2. インストールガイド ​

markdown
## 環境設定

### 1. Node.jsのインストール

**macOS (Homebrewを使用):**

```bash
# Homebrewをインストール(インストール済みの場合は不要)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Node.jsをインストール
brew install node

# インストール確認
node --version
npm --version
```

**Ubuntu/Debian:**

```bash
# パッケージリストを更新
sudo apt update

# Node.jsとnpmをインストール
sudo apt install nodejs npm

# インストール確認
node --version
npm --version
```

**Windows (Chocolateyを使用):**

```powershell
# Chocolateyをインストール(管理者として実行)
Set-ExecutionPolicy Bypass -Scope Process -Force; 
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; 
iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

# Node.jsをインストール
choco install nodejs

# インストール確認
node --version
npm --version
```

3. コード比較 ​

markdown
## リファクタリング前後

**リファクタリング前 (コールバック地獄):**

```javascript
function getUserData(userId, callback) {
    getUser(userId, function(err, user) {
        if (err) {
            callback(err);
            return;
        }
        
        getPosts(user.id, function(err, posts) {
            if (err) {
                callback(err);
                return;
            }
            
            getComments(posts[0].id, function(err, comments) {
                if (err) {
                    callback(err);
                    return;
                }
                
                callback(null, { user, posts, comments });
            });
        });
    });
}
```

**リファクタリング後 (async/await):**

```javascript
async function getUserData(userId) {
    try {
        const user = await getUser(userId);
        const posts = await getPosts(user.id);
        const comments = await getComments(posts[0].id);
        
        return { user, posts, comments };
    } catch (error) {
        throw error;
    }
}
```

HTML出力 ​

囲み付きコードブロックはHTMLに変換されます:

markdown
```javascript
function hello() {
    console.log("Hello");
}
```

変換後:

html
<pre><code class="language-javascript">
function hello() {
    console.log("Hello");
}
</code></pre>

関連構文 ​

練習 ​

以下のコードブロックを作成してみましょう:

  1. 複数のプログラミング言語のコード例
  2. 完全なAPI使用チュートリアル(リクエストとレスポンスを含む)
  3. デプロイスクリプトのドキュメント
  4. データベース設計用のSQLスクリプト

ツールとプラグイン ​

構文強調表示ライブラリ ​

  • Prism.js:軽量な構文強調表示
  • highlight.js:機能豊富なハイライトライブラリ
  • CodeMirror:オンラインコードエディタ
  • Monaco Editor:VS Codeエディタのコア

Markdownプロセッサ ​

  • markdown-it:拡張可能なMarkdownパーサー
  • remark:統一されたMarkdownプロセッサ
  • marked:高速なMarkdownパーサー
  • gray-matter:Front Matterパーサー

エディタプラグイン ​

  • VS Code:Markdownプレビュー拡張
  • Sublime Text:MarkdownEditing
  • Atom:markdown-preview-plus
  • Vim:vim-markdown

Build by www.markdownlang.com