mkdlint 0.11.9

A style checker and lint tool for Markdown/CommonMark files, written in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
# mkdlint Language Server Protocol (LSP)

The mkdlint LSP server provides real-time linting and code actions in your favorite editor.

## Table of Contents

- [Features]#features
- [Installation]#installation
- [Editor Setup]#editor-setup
  - [VS Code]#vs-code
  - [Neovim]#neovim
  - [Emacs]#emacs
  - [Helix]#helix
  - [Zed]#zed
  - [Sublime Text]#sublime-text
- [Architecture]#architecture
- [Capabilities]#capabilities
- [Configuration]#configuration
- [Troubleshooting]#troubleshooting
- [Performance]#performance

## Features

✨ **Real-time Diagnostics**
- Lint as you type with 300ms debouncing
- Instant feedback on save (bypasses debounce)
- UTF-8 aware range calculation

🔧 **Code Actions (Quick Fixes)**
- Individual fixes for each fixable error
- "Fix All" command to apply all fixes at once
- 48/53 rules support auto-fix (90.6% coverage)

📂 **Workspace Aware**
- Automatic config discovery (`.markdownlint.json`, `.yaml`, `.yml`)
- Walks up directory tree to workspace root
- Config caching for performance
- Multi-workspace support

⚡ **Performance**
- Debounced edits prevent excessive re-linting
- In-memory document cache
- Parallel file processing (via mkdlint core)

## Installation

### From Pre-built Binary

Download the latest binary from [GitHub Releases](https://github.com/192d-Wing/mkdlint/releases):

```bash
# Linux x86_64
curl -LO https://github.com/192d-Wing/mkdlint/releases/latest/download/mkdlint-linux-x86_64.tar.gz
tar -xzf mkdlint-linux-x86_64.tar.gz
sudo mv mkdlint mkdlint-lsp /usr/local/bin/

# macOS (Apple Silicon)
curl -LO https://github.com/192d-Wing/mkdlint/releases/latest/download/mkdlint-macos-aarch64.tar.gz
tar -xzf mkdlint-macos-aarch64.tar.gz
sudo mv mkdlint mkdlint-lsp /usr/local/bin/

# Verify
mkdlint-lsp --version
```

### From Source

Build with the `lsp` feature enabled:

```bash
cargo install mkdlint --features lsp

# Binary will be at ~/.cargo/bin/mkdlint-lsp
which mkdlint-lsp
```

### From Repository

```bash
git clone https://github.com/192d-Wing/mkdlint.git
cd mkdlint
cargo build --release --features lsp

# Binary at target/release/mkdlint-lsp
```

## Editor Setup

### VS Code

#### Option 1: Using a Generic LSP Client

Install the [vscode-languageclient](https://marketplace.visualstudio.com/items?itemName=vscode.languageclient) extension, then create a custom extension:

**`.vscode/extensions/mkdlint-lsp/package.json`**:
```json
{
  "name": "mkdlint-lsp",
  "version": "1.0.0",
  "engines": {
    "vscode": "^1.75.0"
  },
  "activationEvents": [
    "onLanguage:markdown"
  ],
  "main": "./out/extension.js",
  "contributes": {
    "configuration": {
      "type": "object",
      "title": "mkdlint",
      "properties": {
        "mkdlint.enable": {
          "type": "boolean",
          "default": true,
          "description": "Enable mkdlint LSP"
        },
        "mkdlint.trace.server": {
          "type": "string",
          "enum": ["off", "messages", "verbose"],
          "default": "off",
          "description": "Trace LSP communication"
        }
      }
    }
  }
}
```

**`.vscode/extensions/mkdlint-lsp/src/extension.ts`**:
```typescript
import * as path from 'path';
import { workspace, ExtensionContext } from 'vscode';
import {
  LanguageClient,
  LanguageClientOptions,
  ServerOptions,
} from 'vscode-languageclient/node';

let client: LanguageClient;

export function activate(context: ExtensionContext) {
  const serverOptions: ServerOptions = {
    command: 'mkdlint-lsp',
    args: [],
  };

  const clientOptions: LanguageClientOptions = {
    documentSelector: [{ scheme: 'file', language: 'markdown' }],
    synchronize: {
      fileEvents: workspace.createFileSystemWatcher('**/.markdownlint{.json,.yaml,.yml,rc}')
    }
  };

  client = new LanguageClient(
    'mkdlint',
    'mkdlint Language Server',
    serverOptions,
    clientOptions
  );

  client.start();
}

export function deactivate(): Thenable<void> | undefined {
  if (!client) {
    return undefined;
  }
  return client.stop();
}
```

Compile and reload VS Code to activate.

#### Option 2: Settings-based (Simpler)

If you have a generic LSP extension, add to `.vscode/settings.json`:

```json
{
  "markdown.validate.enabled": false,
  "lsp.servers": {
    "mkdlint": {
      "command": "mkdlint-lsp",
      "filetypes": ["markdown"],
      "rootPatterns": [".markdownlint.json", ".git"]
    }
  }
}
```

### Neovim

#### Using nvim-lspconfig

Add to your Neovim config (`~/.config/nvim/init.lua` or `~/.config/nvim/lua/lsp.lua`):

```lua
local lspconfig = require('lspconfig')
local configs = require('lspconfig.configs')

-- Define mkdlint LSP config
if not configs.mkdlint then
  configs.mkdlint = {
    default_config = {
      cmd = { 'mkdlint-lsp' },
      filetypes = { 'markdown' },
      root_dir = lspconfig.util.root_pattern(
        '.markdownlint.json',
        '.markdownlint.yaml',
        '.markdownlint.yml',
        '.git'
      ),
      settings = {},
    },
  }
end

-- Setup
lspconfig.mkdlint.setup({
  on_attach = function(client, bufnr)
    -- Enable completion
    vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc')

    -- Keybindings
    local opts = { noremap = true, silent = true, buffer = bufnr }
    vim.keymap.set('n', 'gd', vim.lsp.buf.definition, opts)
    vim.keymap.set('n', 'K', vim.lsp.buf.hover, opts)
    vim.keymap.set('n', '<leader>ca', vim.lsp.buf.code_action, opts)
    vim.keymap.set('n', '<leader>rn', vim.lsp.buf.rename, opts)
    vim.keymap.set('n', '<leader>f', function()
      vim.lsp.buf.format({ async = true })
    end, opts)

    -- Auto-fix on save
    vim.api.nvim_create_autocmd("BufWritePre", {
      buffer = bufnr,
      callback = function()
        -- Request code actions and apply "Fix All"
        vim.lsp.buf.code_action({
          context = { only = { 'source.fixAll' } },
          apply = true,
        })
      end,
    })
  end,
})
```

#### Minimal Config

```lua
require('lspconfig').mkdlint.setup({})
```

### Emacs

#### Using lsp-mode

Add to your Emacs config (`~/.emacs.d/init.el` or `~/.emacs`):

```elisp
(use-package lsp-mode
  :hook ((markdown-mode . lsp))
  :commands lsp
  :config
  (lsp-register-client
   (make-lsp-client
    :new-connection (lsp-stdio-connection "mkdlint-lsp")
    :major-modes '(markdown-mode)
    :server-id 'mkdlint
    :priority 1)))

;; Optional: Enable which-key for LSP bindings
(use-package lsp-ui
  :commands lsp-ui-mode
  :config
  (setq lsp-ui-doc-enable t
        lsp-ui-doc-position 'at-point
        lsp-ui-sideline-enable t))
```

#### Auto-fix on save

```elisp
(add-hook 'markdown-mode-hook
  (lambda ()
    (add-hook 'before-save-hook #'lsp-format-buffer nil t)))
```

### Helix

Add to `~/.config/helix/languages.toml`:

```toml
[[language]]
name = "markdown"
language-servers = ["mkdlint-lsp"]
auto-format = true

[language-server.mkdlint-lsp]
command = "mkdlint-lsp"
```

### Zed

Add to `~/.config/zed/settings.json`:

```json
{
  "lsp": {
    "mkdlint": {
      "binary": {
        "path": "/usr/local/bin/mkdlint-lsp"
      },
      "settings": {}
    }
  },
  "languages": {
    "Markdown": {
      "language_servers": ["mkdlint"]
    }
  }
}
```

### Sublime Text

#### Using LSP Package

1. Install [LSP]https://packagecontrol.io/packages/LSP package
2. Add to `Preferences > Package Settings > LSP > Settings`:

```json
{
  "clients": {
    "mkdlint": {
      "enabled": true,
      "command": ["mkdlint-lsp"],
      "selector": "text.html.markdown",
      "settings": {}
    }
  }
}
```

## Architecture

### Components

```
mkdlint-lsp (binary)
  ↓
MkdlintLanguageServer (backend)
  ├─ DocumentManager (in-memory cache)
  ├─ ConfigManager (config discovery & caching)
  ├─ Debouncer (300ms delay)
  └─ Client (LSP communication)
      ├─ Diagnostics (LintError → LSP Diagnostic)
      ├─ Code Actions (FixInfo → LSP TextEdit)
      └─ Utils (position/range helpers)
```

### Lifecycle

1. **Initialize**: Client sends workspace roots, server stores them
2. **Open Document**: Server caches content, lints immediately
3. **Change Document**: Debounced lint after 300ms
4. **Save Document**: Immediate lint (bypasses debounce)
5. **Close Document**: Remove from cache, clear diagnostics
6. **Shutdown**: Clean up resources

### Config Discovery

For each file:
1. Start at file's directory
2. Look for `.markdownlint.json`, `.yaml`, `.yml`, `.markdownlintrc`
3. Walk up to workspace root
4. Cache result by directory (includes negative results)
5. Apply config to lint options

## Capabilities

The mkdlint LSP server advertises these capabilities:

- **Text Document Sync**: Full document sync
- **Code Action Provider**: Provides quick-fix actions
- **Execute Command Provider**: `mkdlint.fixAll` command
- **Hover Provider**: Rule documentation on hover
- **Document Symbol Provider**: Heading outline for breadcrumbs and navigation

### Supported Methods

| Method | Description |
|--------|-------------|
| `initialize` | Initialize with workspace roots |
| `initialized` | Confirm initialization |
| `shutdown` | Clean shutdown |
| `textDocument/didOpen` | Document opened, lint immediately |
| `textDocument/didChange` | Document changed, debounced lint |
| `textDocument/didSave` | Document saved, immediate lint |
| `textDocument/didClose` | Document closed, clear diagnostics |
| `textDocument/codeAction` | Provide quick-fix actions |
| `textDocument/hover` | Show rule documentation and error details |
| `textDocument/documentSymbol` | Show headings as outline symbols |
| `workspace/executeCommand` | Execute commands (e.g., Fix All) |
| `workspace/didChangeWatchedFiles` | Reload config on file change |

### Planned Features

- [x] `textDocument/hover` - Show rule documentation
- [ ] `textDocument/formatting` - Format entire document
- [x] `textDocument/documentSymbol` - Show headings as symbols
- [x] `workspace/didChangeWatchedFiles` - Reload config on change
- [ ] `workspace/configuration` - Client-provided settings

## Configuration

### Config File Discovery

The LSP server automatically discovers config files in this order:

1. `.markdownlint.json`
2. `.markdownlint.jsonc` (JSON with comments)
3. `.markdownlint.yaml`
4. `.markdownlint.yml`
5. `.markdownlintrc`

Walks up from the file's directory to the workspace root.

### Example Config

**`.markdownlint.json`**:
```json
{
  "default": true,
  "MD013": { "line_length": 120 },
  "MD033": false,
  "MD041": false
}
```

See [Configuration Guide](USER_GUIDE.md#configuration) for full details.

## Troubleshooting

### LSP Server Not Starting

**Check binary exists:**
```bash
which mkdlint-lsp
mkdlint-lsp --version
```

**Check editor LSP logs:**
- **VS Code**: Output → mkdlint Language Server
- **Neovim**: `:LspLog`
- **Emacs**: `*lsp-log*` buffer

**Enable verbose logging:**
```bash
RUST_LOG=debug mkdlint-lsp
```

### No Diagnostics Appearing

1. **File must be saved**: Some editors require save to trigger LSP
2. **Check file extension**: Must be `.md` or `.markdown`
3. **Check for errors in config**: Invalid `.markdownlint.json` will fail silently
4. **Verify workspace root**: LSP needs a workspace root to discover config

### Code Actions Not Working

1. **Only fixable rules show actions**: Check if rule supports auto-fix
2. **Cursor must be on error line**: Position cursor on diagnostic
3. **Try "Fix All" command**: Should always be available if any fixes exist

### Performance Issues

**Increase debounce delay** (future feature):
Currently hardcoded to 300ms, will be configurable.

**Disable expensive rules**:
```json
{
  "MD013": false  // Line length checking can be slow on huge files
}
```

**Large files**:
Files > 10,000 lines may be slow. Consider splitting or excluding from linting.

### Config Not Found

**Check workspace roots:**
```
# In editor LSP logs, look for:
mkdlint LSP initialized with N workspace root(s)
```

If 0 roots, config discovery won't work properly.

**Verify config file name and location:**
```bash
# Must be in or above the file's directory
ls -la .markdownlint.json
```

## Performance

### Benchmarks

| Operation | Time | Notes |
|-----------|------|-------|
| Open document | ~10-50ms | Includes initial lint |
| Change (debounced) | ~5-20ms | After 300ms delay |
| Save | ~5-20ms | Immediate, no debounce |
| Code action request | ~1-5ms | Cache lookup |
| Config discovery | ~1ms | Cached after first lookup |

Times depend on file size and number of errors.

### Optimization Tips

1. **Let debouncing work**: Don't save after every keystroke
2. **Use config to disable unwanted rules**: Faster linting
3. **Cache hits are fast**: Config caching is very efficient
4. **Workspace roots matter**: Proper roots enable config caching

### Memory Usage

- **Per document**: ~5-10 KB (content + cached errors)
- **Config cache**: ~1-2 KB per directory
- **Total overhead**: < 1 MB for typical projects

### Scaling

Tested with:
- ✅ 100+ markdown files in workspace
- ✅ Files up to 10,000 lines
- ✅ Multiple concurrent editors

## Contributing

Want to improve the LSP server? See:
- [CONTRIBUTING.md]../CONTRIBUTING.md - Development guidelines
- [I-PLAN-LSP.md]../I-PLAN-LSP.md - Implementation plan
- [GitHub Issues]https://github.com/192d-Wing/mkdlint/issues - Current work

## License

Apache-2.0 - See [LICENSE](../LICENSE) for details.