Skip to content

Blocchi di Codice Delimitati

I blocchi di codice delimitati sono una funzionalità importante della sintassi estesa di Markdown, che offre capacità di visualizzazione del codice più potenti rispetto ai blocchi di codice base, inclusa l'evidenziazione della sintassi, numeri di riga, nomi file e altre funzionalità avanzate.

Blocchi di Codice Delimitati di Base

Tre Accenti Gravi

Usa tre accenti gravi ``` per creare un blocco di codice:

markdown
```
function hello() {
    console.log("Ciao, Mondo!");
}
```

Risultato renderizzato:

function hello() {
    console.log("Ciao, Mondo!");
}

Tre Tilde

Puoi anche usare tre tilde ~~~ per creare un blocco di codice:

markdown
~~~
function hello() {
    console.log("Ciao, Mondo!");
}
~~~

Risultato renderizzato:

function hello() {
    console.log("Ciao, Mondo!");
}

Evidenziazione della Sintassi

Specificare il Linguaggio di Programmazione

Specifica il nome del linguaggio dopo il marcatore di apertura per abilitare l'evidenziazione della sintassi:

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

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

Risultato renderizzato:

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

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

Esempi di Linguaggi Comuni

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)

# Esempio d'uso
numbers = [3, 6, 8, 10, 1, 2, 1]
print(quicksort(numbers))
```

Risultato renderizzato:

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)

# Esempio d'uso
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);
    }
}
```

Risultato renderizzato:

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("Server avviato sulla porta %s\n", s.port)
    return http.ListenAndServe(":"+s.port, nil)
}

func (s *Server) handleHome(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Benvenuto su Go Server!")
}

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())
}
```

Risultato renderizzato:

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("Server avviato sulla porta %s\n", s.port)
    return http.ListenAndServe(":"+s.port, nil)
}

func (s *Server) handleHome(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Benvenuto su Go Server!")
}

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())
}

Funzionalità Avanzate

Evidenziazione delle Righe

Alcuni processori Markdown supportano l'evidenziazione di righe specifiche:

markdown
```javascript {2,4-6}
function calculateTotal(items) {
    let total = 0; // Questa riga è evidenziata
    
    for (const item of items) { // Queste righe sono evidenziate
        total += item.price * item.quantity;
    } // Fine evidenziazione
    
    return total;
}
```

Mostra Numeri di Riga

Visualizza i numeri di riga del codice:

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

Titolo Nome File

Visualizza il nome del file del codice:

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();
    }
}
```

Visualizzazione Diff nei Blocchi di Codice

Mostra le modifiche del codice:

markdown
```diff
function calculateTax(amount) {
-   return amount * 0.05; // Vecchia aliquota
+   return amount * 0.08; // Nuova aliquota
}

+ // Nuova funzione
+ function calculateDiscount(amount, percentage) {
+     return amount * (percentage / 100);
+ }
```

Risultato renderizzato:

diff
function calculateTax(amount) {
-   return amount * 0.05; // Vecchia aliquota
+   return amount * 0.08; // Nuova aliquota
}

+ // Nuova funzione
+ function calculateDiscount(amount, percentage) {
+     return amount * (percentage / 100);
+ }

Esempi di File di Configurazione

Configurazione 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"
  }
}
```

Risultato renderizzato:

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"
  }
}

Configurazione 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"
```

Risultato renderizzato:

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"

Query SQL

markdown
```sql
-- Crea tabella utenti
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
);

-- Crea indici
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_username ON users(username);

-- Query utenti attivi
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;
```

Risultato renderizzato:

sql
-- Crea tabella utenti
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
);

-- Crea indici
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_username ON users(username);

-- Query utenti attivi
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;

Script e Comandi Shell

Script Bash

markdown
```bash
#!/bin/bash

# Script di deploy
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 "Avvio deploy di ${APP_NAME}..."

# Crea backup
if [ -d "$DEPLOY_DIR" ]; then
    echo "Creo backup in ${BACKUP_DIR}/${CURRENT_DATE}"
    mkdir -p "$BACKUP_DIR"
    cp -r "$DEPLOY_DIR" "${BACKUP_DIR}/${CURRENT_DATE}"
fi

# Ferma servizio
echo "Arresto servizio..."
sudo systemctl stop $APP_NAME || true

# Deploy nuova versione
echo "Deploy nuova versione..."
rm -rf "$DEPLOY_DIR"
mkdir -p "$DEPLOY_DIR"
tar -xzf "${APP_NAME}.tar.gz" -C "$DEPLOY_DIR"

# Installa dipendenze
echo "Installazione dipendenze..."
cd "$DEPLOY_DIR"
npm ci --production

# Avvia servizio
echo "Avvio servizio..."
sudo systemctl start $APP_NAME
sudo systemctl enable $APP_NAME

echo "Deploy completato!"
```

Risultato renderizzato:

bash
#!/bin/bash

# Script di deploy
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 "Avvio deploy di ${APP_NAME}..."

# Crea backup
if [ -d "$DEPLOY_DIR" ]; then
    echo "Creo backup in ${BACKUP_DIR}/${CURRENT_DATE}"
    mkdir -p "$BACKUP_DIR"
    cp -r "$DEPLOY_DIR" "${BACKUP_DIR}/${CURRENT_DATE}"
fi

# Ferma servizio
echo "Arresto servizio..."
sudo systemctl stop $APP_NAME || true

# Deploy nuova versione
echo "Deploy nuova versione..."
rm -rf "$DEPLOY_DIR"
mkdir -p "$DEPLOY_DIR"
tar -xzf "${APP_NAME}.tar.gz" -C "$DEPLOY_DIR"

# Installa dipendenze
echo "Installazione dipendenze..."
cd "$DEPLOY_DIR"
npm ci --production

# Avvia servizio
echo "Avvio servizio..."
sudo systemctl start $APP_NAME
sudo systemctl enable $APP_NAME

echo "Deploy completato!"

Errori Comuni e Soluzioni

1. Numero di Accenti Gravi Non Corrispondente

markdown
❌ Errore:
```javascript
function hello() {
    console.log("Ciao");
}
``  ← Solo due accenti gravi

Corretto:
```javascript
function hello() {
    console.log("Ciao");
}
```  ← Tre accenti gravi

2. Identificatore Linguaggio Errato

markdown
❌ Errore:
```js  ← Alcuni processori non lo riconoscono
function hello() {}
```

✅ Consigliato:
```javascript  ← Usa il nome completo
function hello() {}
```

3. Blocchi di Codice Annidati

markdown
❌ Problema: Non si può visualizzare codice che contiene ```

✅ Soluzione: Usa quattro accenti gravi per racchiudere tre accenti gravi
````markdown
```javascript
console.log("ciao");
```

### 4. Gestione Caratteri Speciali

````markdown
```markdown
<!-- Visualizza sintassi markdown in un blocco di codice markdown -->
\```javascript  ← Escape accenti gravi
code here
\```
```

Elenco Linguaggi Supportati

Linguaggi di Programmazione

LinguaggioIdentificatoreAlias
JavaScriptjavascriptjs
TypeScripttypescriptts
Pythonpythonpy
Javajava
C++cppc++, cxx
C#csharpcs
Gogogolang
Rustrustrs
PHPphp
Rubyrubyrb
Swiftswift
Kotlinkotlinkt

Linguaggi di Markup e Configurazione

LinguaggioIdentificatoreUtilizzo
HTMLhtmlMarkup web
CSScssFoglio di stile
XMLxmlScambio dati
JSONjsonFormato dati
YAMLyaml, ymlFile di configurazione
TOMLtomlFile di configurazione
Markdownmarkdown, mdDocumentazione

Linguaggi Dati e Query

LinguaggioIdentificatoreUtilizzo
SQLsqlQuery database
GraphQLgraphqlQuery API
RrCalcolo statistico
MATLABmatlabCalcolo numerico

Shell e Script

LinguaggioIdentificatoreUtilizzo
Bashbash, shShell Unix
PowerShellpowershell, ps1Shell Windows
Batchbatch, batBatch Windows
DockerfiledockerfileConfigurazione container

Best Practice

1. Scegli l'Identificatore Linguaggio Appropriato

markdown
✅ Consigliato: Usa l'identificatore linguaggio accurato
```typescript
interface User {
    id: number;
    name: string;
}
```

❌ Non consigliato: Usa identificatore errato
```javascript  ← Questo è codice TypeScript
interface User {
    id: number;
    name: string;
}
```

2. Aggiungi Commenti Significativi

markdown
✅ Consigliato: Includi commenti esplicativi
```python
def fibonacci(n):
    """Calcola l'n-esimo numero di Fibonacci"""
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)
```

❌ Non consigliato: Codice senza spiegazione
```python
def fib(n):
    if n <= 1:
        return n
    return fib(n-1) + fib(n-2)
```

3. Mantieni il Codice Conciso

markdown
✅ Consigliato: Mostra la logica principale
```javascript
// Middleware autenticazione utente
function authenticate(req, res, next) {
    const token = req.headers.authorization;
    if (!token) {
        return res.status(401).json({ error: 'Nessun token fornito' });
    }
    // Logica di verifica...
    next();
}
```

❌ Non consigliato: Troppo codice irrilevante
```javascript
// Ometto molto codice non correlato...
```

4. Usa Titoli Nome File

markdown
✅ Consigliato: Mostra nome file
```javascript title="middleware/auth.js"
export function authenticate(req, res, next) {
    // Logica autenticazione
}
```

✅ Consigliato: Mostra nome file di configurazione
```json title="package.json"
{
  "name": "my-app",
  "version": "1.0.0"
}
```

Scenari Pratici di Applicazione

1. Documentazione API

markdown
## API Login Utente

**Esempio di richiesta:**

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

**Esempio di risposta:**

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

**Risposta di errore:**

```json
{
  "success": false,
  "error": {
    "code": "INVALID_CREDENTIALS",
    "message": "Email o password non validi"
  }
}
```

2. Guida all'Installazione

markdown
## Configurazione Ambiente

### 1. Installa Node.js

**macOS (con Homebrew):**

```bash
# Installa Homebrew (se non già installato)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Installa Node.js
brew install node

# Verifica installazione
node --version
npm --version
```

**Ubuntu/Debian:**

```bash
# Aggiorna lista pacchetti
sudo apt update

# Installa Node.js e npm
sudo apt install nodejs npm

# Verifica installazione
node --version
npm --version
```

**Windows (con Chocolatey):**

```powershell
# Installa Chocolatey (esegui come amministratore)
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'))

# Installa Node.js
choco install nodejs

# Verifica installazione
node --version
npm --version
```

3. Confronto Codice

markdown
## Prima e Dopo Refactoring

**Prima (Callback Hell):**

```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 });
            });
        });
    });
}
```

**Dopo (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;
    }
}
```

Output HTML

I blocchi di codice delimitati vengono convertiti in HTML:

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

Convertito in:

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

Sintassi Correlata

Pratica

Prova a creare i seguenti blocchi di codice:

  1. Una raccolta di esempi di codice in più linguaggi di programmazione
  2. Un tutorial API completo (inclusa richiesta e risposta)
  3. Una documentazione di script di deploy
  4. Uno script SQL per la progettazione database

Strumenti e Plugin

Librerie Evidenziazione Sintassi

  • Prism.js: Evidenziazione sintassi leggera
  • highlight.js: Libreria ricca di funzionalità
  • CodeMirror: Editor di codice online
  • Monaco Editor: Core dell'editor VS Code

Processori Markdown

  • markdown-it: Parser Markdown estendibile
  • remark: Processore Markdown unificato
  • marked: Parser Markdown veloce
  • gray-matter: Parser Front Matter

Plugin Editor

  • VS Code: Markdown Preview Enhanced
  • Sublime Text: MarkdownEditing
  • Atom: markdown-preview-plus
  • Vim: vim-markdown

Built by www.markdownlang.com