mdformat-slw 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ """An mdformat plugin for slw-style sentence wrapping."""
2
+
3
+ __version__ = "0.2.0"
4
+
5
+ __plugin_name__ = "slw"
6
+
7
+ # FYI see source code for available interfaces:
8
+ # https://github.com/executablebooks/mdformat/blob/5d9b573ce33bae219087984dd148894c774f41d4/src/mdformat/plugins.py
9
+ from .plugin import POSTPROCESSORS, RENDERERS, add_cli_argument_group, update_mdit
10
+
11
+ __all__ = ("POSTPROCESSORS", "RENDERERS", "add_cli_argument_group", "update_mdit")
@@ -0,0 +1,32 @@
1
+ """General Helpers for configuration management."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any, TypeAlias
7
+
8
+ from . import __plugin_name__
9
+
10
+ ContextOptions: TypeAlias = Mapping[str, Any]
11
+
12
+
13
+ def get_conf(options: ContextOptions, key: str) -> bool | str | int | None:
14
+ """Read setting from mdformat configuration Context.
15
+
16
+ Configuration can be provided via:
17
+ 1. API call: mdformat.text(..., options={key: value})
18
+ 2. CLI/TOML: stored in options["mdformat"]["plugin"]["slw"][key]
19
+
20
+ Args:
21
+ options: Configuration options from mdformat rendering context
22
+ key: Configuration key to retrieve
23
+
24
+ Returns:
25
+ Configuration value (bool, str, int, or None if not found)
26
+
27
+ """
28
+ if (api := options["mdformat"].get(key)) is not None:
29
+ return api # From API
30
+ return (
31
+ options["mdformat"].get("plugin", {}).get(__plugin_name__, {}).get(key)
32
+ ) # from cli_or_toml
@@ -0,0 +1,172 @@
1
+ """Language-specific word lists for abbreviation detection.
2
+
3
+ This module provides suppression word lists for different languages.
4
+ Words in these lists won't trigger sentence wrapping when followed by
5
+ sentence-ending punctuation.
6
+
7
+ Based on slw's approach with Unicode CLDR-inspired lists.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ # Author's Choice (ac) - Curated English list (default)
13
+ # These are common abbreviations that should not trigger sentence breaks
14
+ _AC_SUPPRESSIONS = [
15
+ # Titles
16
+ "Dr",
17
+ "Mr",
18
+ "Mrs",
19
+ "Ms",
20
+ "Prof",
21
+ "Sr",
22
+ "Jr",
23
+ # Time
24
+ "a.m",
25
+ "p.m",
26
+ "A.M",
27
+ "P.M",
28
+ # Latin abbreviations
29
+ "e.g",
30
+ "i.e",
31
+ "etc",
32
+ "et al",
33
+ "vs",
34
+ "viz",
35
+ "cf",
36
+ "ca",
37
+ # Academic/Professional
38
+ "Ph.D",
39
+ "M.D",
40
+ "B.A",
41
+ "M.A",
42
+ "B.S",
43
+ "M.S",
44
+ "D.D.S",
45
+ "Esq",
46
+ # Business
47
+ "Inc",
48
+ "Ltd",
49
+ "Corp",
50
+ "Co",
51
+ "LLC",
52
+ # Geography
53
+ "St",
54
+ "Ave",
55
+ "Blvd",
56
+ "Rd",
57
+ "Mt",
58
+ "Ft",
59
+ # Misc
60
+ "No",
61
+ "Nos",
62
+ "Vol",
63
+ "pp",
64
+ "Fig",
65
+ "Jan",
66
+ "Feb",
67
+ "Mar",
68
+ "Apr",
69
+ "Jun",
70
+ "Jul",
71
+ "Aug",
72
+ "Sep",
73
+ "Sept",
74
+ "Oct",
75
+ "Nov",
76
+ "Dec",
77
+ ]
78
+
79
+ # English (en) - Standard Unicode-based list
80
+ _EN_SUPPRESSIONS = [
81
+ "Dr",
82
+ "Mr",
83
+ "Mrs",
84
+ "Ms",
85
+ "Prof",
86
+ "Sr",
87
+ "Jr",
88
+ "e.g",
89
+ "i.e",
90
+ "etc",
91
+ "vs",
92
+ "Inc",
93
+ "Ltd",
94
+ "Corp",
95
+ "St",
96
+ "Ave",
97
+ ]
98
+
99
+ # German (de) - Common German abbreviations
100
+ _DE_SUPPRESSIONS = [
101
+ "Dr",
102
+ "Prof",
103
+ "Hrn",
104
+ "Fr",
105
+ "Frau",
106
+ "z.B",
107
+ "d.h",
108
+ "u.a",
109
+ "usw",
110
+ "bzw",
111
+ "evtl",
112
+ "ggf",
113
+ "inkl",
114
+ "etc",
115
+ ]
116
+
117
+ # Spanish (es) - Common Spanish abbreviations
118
+ _ES_SUPPRESSIONS = [
119
+ "Dr",
120
+ "Sr",
121
+ "Sra",
122
+ "Srta",
123
+ "D",
124
+ "Dña",
125
+ "p.ej",
126
+ "es decir",
127
+ "etc",
128
+ "vs",
129
+ "S.A",
130
+ "Ltda",
131
+ ]
132
+
133
+ # French (fr) - Common French abbreviations
134
+ _FR_SUPPRESSIONS = [
135
+ "Dr",
136
+ "M",
137
+ "Mme",
138
+ "Mlle",
139
+ "Prof",
140
+ "p.ex",
141
+ "c.-à-d",
142
+ "etc",
143
+ "vs",
144
+ "S.A",
145
+ "Cie",
146
+ ]
147
+
148
+ # Italian (it) - Common Italian abbreviations
149
+ _IT_SUPPRESSIONS = [
150
+ "Dr",
151
+ "Sig",
152
+ "Sig.ra",
153
+ "Prof",
154
+ "es",
155
+ "cioè",
156
+ "ecc",
157
+ "vs",
158
+ "S.p.A",
159
+ ]
160
+
161
+ # Main mapping of language codes to suppression lists
162
+ LANG_SUPPRESSIONS: dict[str, list[str]] = {
163
+ "ac": _AC_SUPPRESSIONS,
164
+ "en": _EN_SUPPRESSIONS,
165
+ "de": _DE_SUPPRESSIONS,
166
+ "es": _ES_SUPPRESSIONS,
167
+ "fr": _FR_SUPPRESSIONS,
168
+ "it": _IT_SUPPRESSIONS,
169
+ }
170
+
171
+ # Default language
172
+ DEFAULT_LANG = "ac"
@@ -0,0 +1,587 @@
1
+ """Sentence wrapping logic inspired by slw."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import logging
7
+ import re
8
+ from typing import TYPE_CHECKING
9
+
10
+ from ._helpers import get_conf
11
+ from ._language_data import DEFAULT_LANG, LANG_SUPPRESSIONS
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ if TYPE_CHECKING:
16
+ from collections.abc import Mapping
17
+ from typing import Any
18
+
19
+ from mdformat.renderer import RenderContext, RenderTreeNode
20
+
21
+ ContextOptions = Mapping[str, Any]
22
+
23
+ # Default configuration constants
24
+ DEFAULT_SENTENCE_MARKERS = ".!?:"
25
+
26
+
27
+ class ConfigurationError(ValueError):
28
+ """Raised when configuration values are invalid."""
29
+
30
+
31
+ def _validate_sentence_markers(markers: str) -> None:
32
+ """Validate sentence markers string.
33
+
34
+ Args:
35
+ markers: String of sentence ending characters
36
+
37
+ Raises (via _validate_sentence_markers):
38
+ ConfigurationError: If markers is empty or invalid
39
+
40
+ """
41
+ if not markers:
42
+ msg = "sentence_markers cannot be empty"
43
+ raise ConfigurationError(msg)
44
+ if len(markers) > 50: # noqa: PLR2004
45
+ msg = f"sentence_markers too long (max 50 chars): {len(markers)}"
46
+ raise ConfigurationError(msg)
47
+
48
+
49
+ @functools.lru_cache(maxsize=128)
50
+ def _compile_sentence_pattern(sentence_markers: str) -> re.Pattern[str]:
51
+ """Compile regex pattern for sentence ending detection.
52
+
53
+ Compiles regex pattern with standard quantifiers for Python 3.10+ compatibility
54
+ The pattern is cached to improve performance.
55
+
56
+ Args:
57
+ sentence_markers: String of characters that mark sentence endings
58
+
59
+ Returns:
60
+ Compiled regex pattern
61
+
62
+ """
63
+ _validate_sentence_markers(sentence_markers)
64
+ marker_class = re.escape(sentence_markers)
65
+ # Note: Using standard quantifiers (*) - possessive quantifiers not available in Python 3.10
66
+ # Pattern: (marker)(optional closing chars)(whitespace)
67
+ pattern = r"([" + marker_class + r"])(\s*[\"'\)\]\}]*)\s+"
68
+ return re.compile(pattern)
69
+
70
+
71
+ def should_wrap_sentences(options: ContextOptions) -> bool:
72
+ """Check if sentence wrapping is enabled via CLI or config.
73
+
74
+ Sentence wrapping is ENABLED by default. Use --no-wrap-sentences to disable.
75
+
76
+ Args:
77
+ options: Configuration options from mdformat context
78
+
79
+ Returns:
80
+ True if sentence wrapping is enabled (default: True)
81
+
82
+ """
83
+ no_wrap = get_conf(options, "no_wrap_sentences")
84
+ if no_wrap is not None:
85
+ return not bool(no_wrap)
86
+ return True # Default: enabled
87
+
88
+
89
+ def get_sentence_markers(options: ContextOptions) -> str:
90
+ """Get sentence ending markers from config.
91
+
92
+ Args:
93
+ options: Configuration options from mdformat context
94
+
95
+ Returns:
96
+ String of sentence ending characters (default: .!?:)
97
+
98
+ Raises (via _validate_sentence_markers):
99
+ ConfigurationError: If markers are invalid
100
+
101
+ """
102
+ markers = get_conf(options, "slw_markers")
103
+ result = str(markers) if markers is not None else DEFAULT_SENTENCE_MARKERS
104
+ _validate_sentence_markers(result)
105
+ return result
106
+
107
+
108
+ def get_slw_wrap_width(options: ContextOptions) -> int:
109
+ """Get line wrap width from slw's --slw-wrap setting.
110
+
111
+ Args:
112
+ options: Configuration options from mdformat context
113
+
114
+ Returns:
115
+ Maximum line width in characters, or 0 to disable wrapping (default: 80)
116
+
117
+ """
118
+ wrap_width = get_conf(options, "slw_wrap")
119
+ return int(wrap_width) if wrap_width is not None else 80
120
+
121
+
122
+ def _get_suppression_words(options: ContextOptions) -> set[str]:
123
+ """Build complete set of words that suppress sentence wrapping.
124
+
125
+ Combines language-specific defaults with custom suppressions/ignores.
126
+ Handles case sensitivity based on configuration.
127
+
128
+ Args:
129
+ options: Configuration options from mdformat context
130
+
131
+ Returns:
132
+ Set of words that should not trigger sentence breaks
133
+
134
+ """
135
+ mode = get_conf(options, "abbreviations_mode")
136
+ if mode is None:
137
+ mode = "default"
138
+ mode = str(mode)
139
+
140
+ # Mode: off - disable all abbreviation detection
141
+ if mode == "off":
142
+ return set()
143
+
144
+ # Start with language-specific defaults
145
+ words: set[str] = set()
146
+ if mode in {"default", "extend"}:
147
+ lang_str = get_conf(options, "lang")
148
+ langs = str(lang_str).split() if lang_str else [DEFAULT_LANG]
149
+ for lang in langs:
150
+ words.update(LANG_SUPPRESSIONS.get(lang, []))
151
+
152
+ # Handle custom abbreviations
153
+ custom = get_conf(options, "abbreviations")
154
+ if custom:
155
+ # Parse custom abbreviations (comma-separated string)
156
+ custom_words = str(custom).split(",")
157
+ custom_words = [w.strip() for w in custom_words]
158
+
159
+ if mode == "override":
160
+ words = set(custom_words)
161
+ else: # extend or default mode
162
+ words.update(custom_words)
163
+
164
+ # Add extra suppressions
165
+ suppressions = get_conf(options, "suppressions")
166
+ if suppressions:
167
+ supp_words = str(suppressions).split()
168
+ words.update(supp_words)
169
+
170
+ # Remove ignored words
171
+ ignores = get_conf(options, "ignores")
172
+ if ignores:
173
+ ignore_words = str(ignores).split()
174
+ words -= set(ignore_words)
175
+
176
+ # Handle case sensitivity
177
+ case_sensitive = get_conf(options, "case_sensitive")
178
+ if not case_sensitive:
179
+ # Convert to lowercase for case-insensitive matching
180
+ words = {w.lower() for w in words}
181
+
182
+ return words
183
+
184
+
185
+ def _wrap_long_line(line: str, max_width: int) -> list[str]:
186
+ """Wrap a single long line preserving indentation.
187
+
188
+ Per guidance.md: "Wrap lines that are longer than the maximum line width,
189
+ if set, without splitting words or splitting at non-breaking spaces while
190
+ also keeping indents in tact."
191
+
192
+ Args:
193
+ line: The line to wrap
194
+ max_width: Maximum width in characters
195
+
196
+ Returns:
197
+ List of wrapped lines with preserved indentation
198
+
199
+ """
200
+ # Extract leading whitespace (indentation)
201
+ indent_match = re.match(r"^(\s*)", line)
202
+ indent = indent_match.group(1) if indent_match else ""
203
+ content = line[len(indent) :]
204
+
205
+ # Don't wrap if line fits within max_width
206
+ if len(line) <= max_width:
207
+ return [line]
208
+
209
+ # Split on regular spaces but NOT on non-breaking spaces (U+00A0)
210
+ # Use a pattern that treats nbsp as part of the word
211
+ nbsp = "\u00a0"
212
+ # Replace nbsp with a placeholder, split, then restore
213
+ # Note: Use \x01 instead of \x00 because mdformat uses \x00 for FILLER/WRAP_POINT
214
+ placeholder = "\x01"
215
+ content_normalized = content.replace(nbsp, placeholder)
216
+ words = content_normalized.split()
217
+ # Restore nbsp in each word
218
+ words = [w.replace(placeholder, nbsp) for w in words]
219
+
220
+ wrapped_lines = []
221
+ current_line: list[str] = []
222
+ # Start with indent length
223
+ current_length = len(indent)
224
+
225
+ for word in words:
226
+ word_len = len(word)
227
+ # Calculate space needed: word length + 1 for space (if not first word)
228
+ space_needed = word_len + (1 if current_line else 0)
229
+
230
+ if current_length + space_needed > max_width and current_line:
231
+ # Current line would exceed max_width, flush it with indent
232
+ wrapped_lines.append(indent + " ".join(current_line))
233
+ current_line = [word]
234
+ # Reset length to indent + word
235
+ current_length = len(indent) + word_len
236
+ else:
237
+ # Add word to current line
238
+ current_line.append(word)
239
+ current_length += space_needed
240
+
241
+ if current_line:
242
+ wrapped_lines.append(indent + " ".join(current_line))
243
+
244
+ return wrapped_lines
245
+
246
+
247
+ def _find_protected_regions(text: str) -> list[tuple[int, int]]: # noqa: C901, PLR0912, PLR0915
248
+ """Find regions where sentence wrapping should not occur.
249
+
250
+ Per guidance.md: "Not in a context where auto-wrapping is possible:
251
+ - Inline code, links, definition lists, etc."
252
+
253
+ Returns:
254
+ List of (start, end) tuples marking protected character positions
255
+
256
+ """
257
+ protected = []
258
+
259
+ # Find inline code spans: `code`
260
+ # Handle both single and multiple backticks
261
+ i = 0
262
+ while i < len(text):
263
+ if text[i] == "`":
264
+ # Count consecutive backticks
265
+ backtick_count = 0
266
+ start = i
267
+ while i < len(text) and text[i] == "`":
268
+ backtick_count += 1
269
+ i += 1
270
+
271
+ # Find matching close
272
+ close_start = i
273
+ while i < len(text):
274
+ if text[i] == "`":
275
+ close_count = 0
276
+ while i < len(text) and text[i] == "`":
277
+ close_count += 1
278
+ i += 1
279
+ if close_count == backtick_count:
280
+ # Found matching close - protect entire span
281
+ protected.append((start, i))
282
+ break
283
+ else:
284
+ i += 1
285
+ else:
286
+ # No matching close found - unclosed code span, skip
287
+ i = close_start
288
+ else:
289
+ i += 1
290
+
291
+ # Find links: [text](url) or [text][ref]
292
+ # Pattern: \[...\](\(...\)|[...])
293
+ i = 0
294
+ while i < len(text): # noqa: PLR1702
295
+ if text[i] == "[":
296
+ bracket_start = i
297
+ i += 1
298
+ # Find closing ]
299
+ depth = 1
300
+ while i < len(text) and depth > 0:
301
+ if text[i] == "[":
302
+ depth += 1
303
+ elif text[i] == "]":
304
+ depth -= 1
305
+ i += 1
306
+
307
+ if depth == 0 and i < len(text):
308
+ # Found ], check for ( or [
309
+ if text[i] == "(":
310
+ # Inline link: [text](url)
311
+ i += 1
312
+ depth = 1
313
+ while i < len(text) and depth > 0:
314
+ if text[i] == "(":
315
+ depth += 1
316
+ elif text[i] == ")":
317
+ depth -= 1
318
+ i += 1
319
+ if depth == 0:
320
+ # Complete link found
321
+ protected.append((bracket_start, i))
322
+ elif text[i] == "[":
323
+ # Reference link: [text][ref]
324
+ i += 1
325
+ depth = 1
326
+ while i < len(text) and depth > 0:
327
+ if text[i] == "[":
328
+ depth += 1
329
+ elif text[i] == "]":
330
+ depth -= 1
331
+ i += 1
332
+ if depth == 0:
333
+ # Complete reference link found
334
+ protected.append((bracket_start, i))
335
+ else:
336
+ i += 1
337
+
338
+ return protected
339
+
340
+
341
+ def _is_position_protected(pos: int, protected_regions: list[tuple[int, int]]) -> bool:
342
+ """Check if a position falls within any protected region.
343
+
344
+ Args:
345
+ pos: Character position to check
346
+ protected_regions: List of (start, end) tuples
347
+
348
+ Returns:
349
+ True if position is protected, False otherwise
350
+
351
+ """
352
+ return any(start <= pos < end for start, end in protected_regions)
353
+
354
+
355
+ def _replace_spaces_in_link_text(text: str) -> str: # noqa: C901, PLR0912
356
+ """Replace spaces in link text with non-breaking spaces.
357
+
358
+ Per guidance.md: "Before line wrapping, replace all spaces in link texts
359
+ by non-breaking spaces (and similar inline content that can't be wrapped)"
360
+
361
+ Args:
362
+ text: Text to process
363
+
364
+ Returns:
365
+ Text with spaces in link text replaced by nbsp (U+00A0)
366
+
367
+ """
368
+ nbsp = "\u00a0"
369
+ result = []
370
+ i = 0
371
+
372
+ while i < len(text): # noqa: PLR1702
373
+ if text[i] == "[":
374
+ # Start of potential link
375
+ result.append(text[i])
376
+ i += 1
377
+
378
+ # Find closing ]
379
+ depth = 1
380
+ link_text_chars = []
381
+ while i < len(text) and depth > 0:
382
+ if text[i] == "[":
383
+ depth += 1
384
+ link_text_chars.append(text[i])
385
+ elif text[i] == "]":
386
+ depth -= 1
387
+ if depth > 0:
388
+ link_text_chars.append(text[i])
389
+ elif text[i] == " ":
390
+ # Replace space with nbsp in link text
391
+ link_text_chars.append(nbsp)
392
+ else:
393
+ link_text_chars.append(text[i])
394
+ i += 1
395
+
396
+ # Add link text with nbsp replacements
397
+ result.extend(link_text_chars)
398
+
399
+ if depth == 0:
400
+ # Found closing ], add it
401
+ result.append("]")
402
+
403
+ # Check if this is actually a link (has ( or [ following)
404
+ if i < len(text) and text[i] in {"(", "["}:
405
+ # Copy the rest of the link (URL or reference) as-is
406
+ open_char = text[i]
407
+ close_char = ")" if open_char == "(" else "]"
408
+ result.append(text[i])
409
+ i += 1
410
+ depth = 1
411
+
412
+ while i < len(text) and depth > 0:
413
+ if text[i] == open_char:
414
+ depth += 1
415
+ elif text[i] == close_char:
416
+ depth -= 1
417
+ result.append(text[i])
418
+ i += 1
419
+ else:
420
+ result.append(text[i])
421
+ i += 1
422
+
423
+ return "".join(result)
424
+
425
+
426
+ def _collapse_whitespace(text: str) -> str:
427
+ """Collapse consecutive whitespace while preserving non-breaking spaces.
428
+
429
+ Per guidance.md algorithm:
430
+ - Collapse consecutive whitespace into single space
431
+ - Preserve non-breaking spaces (U+00A0)
432
+ - Preserve linebreaks preceded by non-breaking spaces
433
+
434
+ Args:
435
+ text: Text to process
436
+
437
+ Returns:
438
+ Text with collapsed whitespace
439
+
440
+ """
441
+ # Non-breaking space character (U+00A0)
442
+ nbsp = "\u00a0"
443
+
444
+ # Replace sequences of regular spaces with single space
445
+ # But preserve non-breaking spaces and their adjacent linebreaks
446
+ result = []
447
+ i = 0
448
+ while i < len(text):
449
+ char = text[i]
450
+
451
+ if char == nbsp:
452
+ # Preserve non-breaking space
453
+ result.append(char)
454
+ i += 1
455
+ # If followed by newline, preserve it too
456
+ if i < len(text) and text[i] == "\n":
457
+ result.append(text[i])
458
+ i += 1
459
+ elif char in " \t":
460
+ # Collapse consecutive regular whitespace (spaces/tabs) to single space
461
+ result.append(" ")
462
+ i += 1
463
+ while i < len(text) and text[i] in " \t":
464
+ i += 1
465
+ else:
466
+ result.append(char)
467
+ i += 1
468
+
469
+ return "".join(result)
470
+
471
+
472
+ def wrap_sentences( # noqa: C901
473
+ text: str,
474
+ _node: RenderTreeNode,
475
+ context: RenderContext,
476
+ ) -> str:
477
+ """Wrap text by inserting line breaks after sentences.
478
+
479
+ This is inspired by slw's sentence-wrapping behavior:
480
+ - Insert line breaks after sentence-ending punctuation
481
+ - Collapse consecutive whitespace per guidance.md
482
+ - Optionally wrap long lines using --slw-wrap setting
483
+ - Preserve existing formatting for code blocks and special syntax
484
+ - Respect abbreviations and suppression words
485
+
486
+ Note: The _node parameter is required by mdformat's postprocessor
487
+ interface but is not used in this implementation.
488
+
489
+ Args:
490
+ text: The rendered text to process
491
+ _node: The syntax tree node being rendered (required by interface)
492
+ context: The rendering context with configuration options
493
+
494
+ Returns:
495
+ The text with sentence breaks applied
496
+
497
+ Raises (via _validate_sentence_markers):
498
+ ConfigurationError: If configuration values are invalid
499
+
500
+ """
501
+ if not should_wrap_sentences(context.options):
502
+ return text
503
+
504
+ # Don't wrap if text is empty or just whitespace
505
+ if not text or not text.strip():
506
+ return text
507
+
508
+ # Warn if mdformat's --wrap is set (potential conflict)
509
+ mdformat_wrap = context.options.get("mdformat", {}).get("wrap")
510
+ if mdformat_wrap is not None and mdformat_wrap not in {"keep", None}:
511
+ logger.warning(
512
+ "mdformat's --wrap is set to '%s'. "
513
+ "Consider using --wrap=keep to avoid conflicts with slw sentence wrapping. "
514
+ "Use --slw-wrap instead for line width control.",
515
+ mdformat_wrap,
516
+ )
517
+
518
+ # Step 1: Collapse whitespace (per guidance.md)
519
+ text = _collapse_whitespace(text)
520
+
521
+ # Step 2: Find protected regions (inline code, links) per guidance.md
522
+ protected_regions = _find_protected_regions(text)
523
+
524
+ sentence_markers = get_sentence_markers(context.options)
525
+ wrap_width = get_slw_wrap_width(context.options)
526
+ suppression_words = _get_suppression_words(context.options)
527
+ case_sensitive = get_conf(context.options, "case_sensitive")
528
+
529
+ # Pattern to find potential sentence boundaries
530
+ marker_class = re.escape(sentence_markers)
531
+ # Match: marker + optional closing chars + whitespace
532
+ boundary_pattern = re.compile(r"([" + marker_class + r"])(\s*[\"'\)\]\}]*)\s+")
533
+
534
+ def _replace_with_newline(match: re.Match[str]) -> str:
535
+ """Replace sentence ending with newline, checking suppressions and protection."""
536
+ marker = match.group(1) # Sentence marker
537
+ closing = match.group(2) # Closing chars
538
+
539
+ # Get position of the sentence marker
540
+ marker_pos = match.start() + match.group(0).index(marker)
541
+
542
+ # Check if marker is in a protected region (inline code, link)
543
+ if _is_position_protected(marker_pos, protected_regions):
544
+ return match.group(0)
545
+
546
+ # Get text before this match to check for suppression words
547
+ start_pos = match.start()
548
+ text_before = text[:start_pos]
549
+
550
+ # Check if any suppression word appears at the end of text_before
551
+ if suppression_words:
552
+ for supp_word in suppression_words:
553
+ # Build pattern to check if suppression word appears before marker
554
+ # Handle both "word." and "word" cases
555
+ if case_sensitive:
556
+ check_pattern = re.escape(supp_word)
557
+ else:
558
+ check_pattern = re.escape(supp_word)
559
+
560
+ # Check if text_before ends with this suppression word
561
+ # Allow for period-separated abbreviations like "p.m"
562
+ pattern_to_check = r"\b" + check_pattern.replace(r"\.", r"\.") + r"$"
563
+ if case_sensitive:
564
+ if re.search(pattern_to_check, text_before):
565
+ return match.group(0)
566
+ elif re.search(pattern_to_check, text_before, re.IGNORECASE):
567
+ return match.group(0)
568
+
569
+ # No suppression match - wrap with newline
570
+ return f"{marker}{closing}\n"
571
+
572
+ # Apply sentence breaks
573
+ wrapped = boundary_pattern.sub(_replace_with_newline, text)
574
+
575
+ # Step 3: Replace spaces in link text with non-breaking spaces (per guidance.md)
576
+ # This prevents line wrapping from breaking within link text
577
+ wrapped = _replace_spaces_in_link_text(wrapped)
578
+
579
+ # Step 4: Wrap long lines using --slw-wrap setting (per guidance.md)
580
+ if wrap_width > 0:
581
+ lines = wrapped.split("\n")
582
+ wrapped_lines = []
583
+ for line in lines:
584
+ wrapped_lines.extend(_wrap_long_line(line, wrap_width))
585
+ wrapped = "\n".join(wrapped_lines)
586
+
587
+ return wrapped
mdformat_slw/plugin.py ADDED
@@ -0,0 +1,126 @@
1
+ """Public Extension for slw-style sentence wrapping.
2
+
3
+ This module provides the mdformat plugin interface for sentence wrapping
4
+ functionality. It registers CLI arguments and postprocessors that wrap
5
+ text by inserting line breaks after sentence-ending punctuation.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ from collections.abc import Mapping
12
+
13
+ from markdown_it import MarkdownIt
14
+ from mdformat.renderer.typing import Postprocess, Render
15
+
16
+ from ._sentence_wrapper import wrap_sentences
17
+
18
+
19
+ def add_cli_argument_group(group: argparse._ArgumentGroup) -> None:
20
+ """Add options to the mdformat CLI.
21
+
22
+ Configuration is stored in `mdit.options["mdformat"]["plugin"]["slw"]`
23
+
24
+ Note: When using --slw-wrap, consider disabling mdformat's line wrapping
25
+ with --wrap=keep to avoid conflicts between the two wrapping mechanisms.
26
+
27
+ Args:
28
+ group: Argument group to add options to
29
+
30
+ """
31
+ group.add_argument(
32
+ "--no-wrap-sentences",
33
+ action="store_const",
34
+ const=True,
35
+ help="Disable slw sentence wrapping (enabled by default)",
36
+ )
37
+ group.add_argument(
38
+ "--slw-markers",
39
+ type=str,
40
+ default=".!?:",
41
+ help="Characters that mark sentence endings for slw (default: .!?:)",
42
+ )
43
+ group.add_argument(
44
+ "--slw-wrap",
45
+ type=int,
46
+ default=80,
47
+ help="Wrap lines at specified width (default: 80). "
48
+ "Set to 0 to disable. Use with --wrap=keep to disable mdformat's wrapping.",
49
+ )
50
+ group.add_argument(
51
+ "--slw-lang",
52
+ type=str,
53
+ dest="lang",
54
+ default="ac",
55
+ help="Space-separated language codes for abbreviation lists "
56
+ "(default: ac). Supported: ac, en, de, es, fr, it",
57
+ )
58
+ group.add_argument(
59
+ "--slw-abbreviations-mode",
60
+ type=str,
61
+ dest="abbreviations_mode",
62
+ choices=["default", "off", "extend", "override"],
63
+ default="default",
64
+ help="Abbreviation detection mode: default (use built-in lists), "
65
+ "off (disable), extend (add custom to built-in), "
66
+ "override (replace built-in with custom)",
67
+ )
68
+ group.add_argument(
69
+ "--slw-abbreviations",
70
+ type=str,
71
+ dest="abbreviations",
72
+ help="Comma-separated custom abbreviations to extend or override defaults",
73
+ )
74
+ group.add_argument(
75
+ "--slw-suppressions",
76
+ type=str,
77
+ dest="suppressions",
78
+ help="Space-separated words to add to suppression list",
79
+ )
80
+ group.add_argument(
81
+ "--slw-ignores",
82
+ type=str,
83
+ dest="ignores",
84
+ help="Space-separated words to remove from suppression list",
85
+ )
86
+ group.add_argument(
87
+ "--slw-case-sensitive",
88
+ action="store_const",
89
+ const=True,
90
+ dest="case_sensitive",
91
+ help="Enable case-sensitive abbreviation matching (default: case-insensitive)",
92
+ )
93
+
94
+
95
+ def update_mdit(mdit: MarkdownIt) -> None:
96
+ """Update the markdown-it parser.
97
+
98
+ The slw plugin doesn't add new markdown syntax, so no parser
99
+ modifications are needed. All functionality is implemented via
100
+ postprocessors that run after rendering.
101
+
102
+ Args:
103
+ mdit: The markdown-it parser instance (unused)
104
+
105
+ """
106
+ # No markdown-it plugins needed for sentence wrapping
107
+ # This function is required by mdformat's plugin interface
108
+
109
+
110
+ # A mapping from syntax tree node type to a function that renders it.
111
+ # This can be used to overwrite renderer functions of existing syntax
112
+ # or add support for new syntax.
113
+ # The slw plugin doesn't need custom renderers, only postprocessors.
114
+ RENDERERS: Mapping[str, Render] = {}
115
+
116
+ # A mapping from `RenderTreeNode.type` to a `Postprocess` that does
117
+ # postprocessing for the output of the `Render` function. Unlike
118
+ # `Render` funcs, `Postprocess` funcs are collaborative: any number of
119
+ # plugins can define a postprocessor for a syntax type and all of them
120
+ # will run in series.
121
+ #
122
+ # Apply sentence wrapping to paragraphs and other text-containing nodes.
123
+ # The postprocessor is active by default; use --no-wrap-sentences to disable.
124
+ POSTPROCESSORS: Mapping[str, Postprocess] = {
125
+ "paragraph": wrap_sentences,
126
+ }
mdformat_slw/py.typed ADDED
File without changes
@@ -0,0 +1,264 @@
1
+ Metadata-Version: 2.4
2
+ Name: mdformat_slw
3
+ Version: 0.2.0
4
+ Summary: An mdformat plugin for slw
5
+ Keywords: markdown,markdown-it,mdformat,mdformat_plugin_template
6
+ Author: kyleking
7
+ Author-email: kyleking <dev.act.kyle@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
14
+ Requires-Dist: mdformat>=0.7.19
15
+ Requires-Dist: mdit-py-plugins>=0.4.1
16
+ Requires-Dist: pytest>=9.0.1 ; extra == 'test'
17
+ Requires-Dist: pytest-beartype>=0.2.0 ; extra == 'test'
18
+ Requires-Dist: pytest-cov>=7.0.0 ; extra == 'test'
19
+ Requires-Python: >=3.10.0
20
+ Project-URL: Bug Tracker, https://github.com/kyleking/mdformat-slw/issues
21
+ Project-URL: Changelog, https://github.com/kyleking/mdformat-slw/releases
22
+ Project-URL: homepage, https://github.com/kyleking/mdformat-slw
23
+ Provides-Extra: test
24
+ Description-Content-Type: text/markdown
25
+
26
+ # mdformat-slw
27
+
28
+ [![Build Status][ci-badge]][ci-link] [![PyPI version][pypi-badge]][pypi-link]
29
+
30
+ An [mdformat](https://github.com/executablebooks/mdformat) plugin for semantic line wrapping (slw).
31
+
32
+ This plugin wraps markdown text by inserting line breaks after sentence-ending punctuation, making diffs cleaner and easier to review.
33
+
34
+ ## Features
35
+
36
+ - **Automatic sentence wrapping** at configurable punctuation marks (default: `.!?:`)
37
+ - **Enabled by default** - no flags needed to activate
38
+ - Optional maximum line width enforcement with `--slw-wrap`
39
+ - Preserves markdown formatting (bold, italic, links, etc.)
40
+ - Handles edge cases: quoted text, parentheses, brackets
41
+
42
+ ## `mdformat` Usage
43
+
44
+ Add this package wherever you use `mdformat` and the plugin will be auto-recognized. Sentence wrapping is **enabled by default**. See [additional information on `mdformat` plugins here](https://mdformat.readthedocs.io/en/stable/users/plugins.html)
45
+
46
+ ### CLI
47
+
48
+ ```sh
49
+ # Sentence wrapping enabled by default
50
+ mdformat document.md
51
+
52
+ # With line width enforcement
53
+ mdformat document.md --slw-wrap 80 --wrap=keep
54
+
55
+ # Disable sentence wrapping
56
+ mdformat document.md --no-wrap-sentences
57
+ ```
58
+
59
+ #### Options
60
+
61
+ **Basic Options:**
62
+
63
+ - `--no-wrap-sentences`: Disable sentence wrapping (enabled by default)
64
+ - `--slw-markers TEXT`: Characters that mark sentence endings (default: `.!?:`)
65
+ - `--slw-wrap INTEGER`: Maximum line width for wrapping (default: 80)
66
+
67
+ **Abbreviation Detection:**
68
+
69
+ - `--slw-lang TEXT`: Space-separated language codes for abbreviation lists (default: `ac`)
70
+ - Supported: `ac` (all-caps only), `en`, `de`, `es`, `fr`, `it`
71
+ - `--slw-abbreviations-mode TEXT`: Abbreviation detection mode (default: `default`)
72
+ - `default`: Use built-in language lists
73
+ - `off`: Disable abbreviation detection
74
+ - `extend`: Add custom abbreviations to built-in lists
75
+ - `override`: Replace built-in lists with custom abbreviations
76
+ - `--slw-abbreviations TEXT`: Comma-separated custom abbreviations (e.g., `Dr.,Prof.,etc.`)
77
+ - `--slw-suppressions TEXT`: Space-separated words to add to suppression list
78
+ - `--slw-ignores TEXT`: Space-separated words to remove from suppression list
79
+ - `--slw-case-sensitive`: Enable case-sensitive abbreviation matching (default: case-insensitive)
80
+
81
+ > **Note:** When using `--slw-wrap`, consider adding `--wrap=keep` to disable mdformat's built-in line wrapping and avoid conflicts.
82
+
83
+ ### Configuration File
84
+
85
+ Create a `.mdformat.toml` file in your project root:
86
+
87
+ ```toml
88
+ [plugin.slw]
89
+ # Disable sentence wrapping (enabled by default)
90
+ no_wrap_sentences = false
91
+
92
+ # Customize sentence markers
93
+ slw_markers = ".!?:"
94
+
95
+ # Set line width wrapping (default: 80)
96
+ slw_wrap = 80
97
+
98
+ # Configure abbreviation detection
99
+ lang = "en de" # Use English and German abbreviations
100
+ abbreviations_mode = "extend" # Add custom to built-in lists
101
+ abbreviations = "Dr.,Prof.,etc." # Custom abbreviations
102
+ case_sensitive = false # Case-insensitive matching (default)
103
+
104
+ # Recommended: disable mdformat's wrapping to avoid conflicts
105
+ [mdformat]
106
+ wrap = "keep"
107
+ ```
108
+
109
+ ### pre-commit / prek
110
+
111
+ ```yaml
112
+ repos:
113
+ - repo: https://github.com/executablebooks/mdformat
114
+ rev: 1.0.0
115
+ hooks:
116
+ - id: mdformat
117
+ additional_dependencies:
118
+ - mdformat-slw
119
+ ```
120
+
121
+ ### uvx
122
+
123
+ ```sh
124
+ uvx --with mdformat-slw mdformat
125
+ ```
126
+
127
+ Or with pipx:
128
+
129
+ ```sh
130
+ pipx install mdformat
131
+ pipx inject mdformat mdformat-slw
132
+ mdformat document.md
133
+ ```
134
+
135
+ ### Python API
136
+
137
+ ```python
138
+ import mdformat
139
+
140
+ text = """
141
+ This is a test. It has multiple sentences! Does it work?
142
+ """
143
+
144
+ # Sentence wrapping enabled by default
145
+ result = mdformat.text(text, extensions={"slw"})
146
+
147
+ print(result)
148
+ # Output:
149
+ # This is a test.
150
+ # It has multiple sentences!
151
+ # Does it work?
152
+
153
+ # With line width wrapping
154
+ result = mdformat.text(
155
+ text,
156
+ extensions={"slw"},
157
+ options={"slw_wrap": 80}
158
+ )
159
+
160
+ # Disable sentence wrapping
161
+ result = mdformat.text(
162
+ text,
163
+ extensions={"slw"},
164
+ options={"no_wrap_sentences": True}
165
+ )
166
+ ```
167
+
168
+ ## Example
169
+
170
+ ### Basic Wrapping
171
+
172
+ **Input:**
173
+
174
+ ```markdown
175
+ This is a long sentence. It contains multiple clauses! Does it work? Yes it does.
176
+ ```
177
+
178
+ **Output (default behavior):**
179
+
180
+ ```markdown
181
+ This is a long sentence.
182
+ It contains multiple clauses!
183
+ Does it work?
184
+ Yes it does.
185
+ ```
186
+
187
+ ### Abbreviation Detection
188
+
189
+ **Input:**
190
+
191
+ ```markdown
192
+ Dr. Smith met with Prof. Johnson at 3 p.m. They discussed the project etc. and other topics.
193
+ ```
194
+
195
+ **Output (abbreviations preserved):**
196
+
197
+ ```markdown
198
+ Dr. Smith met with Prof. Johnson at 3 p.m.
199
+ They discussed the project etc. and other topics.
200
+ ```
201
+
202
+ ### Link Protection
203
+
204
+ **Input:**
205
+
206
+ ```markdown
207
+ Check [example.com](https://example.com). Use `config.json` for settings. Done!
208
+ ```
209
+
210
+ **Output (links and code preserved):**
211
+
212
+ ```markdown
213
+ Check [example.com](https://example.com).
214
+ Use `config.json` for settings.
215
+ Done!
216
+ ```
217
+
218
+ ## How It Works
219
+
220
+ ### Wrapping Rules
221
+
222
+ When one of the limited number of characters (`.!?:` by default) which serve as end-of-sentence markers occur alone, mdformat-slw will wrap **except** when:
223
+
224
+ 1. Not in a context where auto-wrapping is possible:
225
+ - Inline code, links, definition lists, etc.
226
+ - Code Blocks
227
+ - Tables
228
+ - HTML Blocks
229
+ 1. When the wrapped term is an abbreviation:
230
+ - Multiple end-of-sentence markers occur (such as `p.m.` or `e.g.`)
231
+ - Identified as an abbreviation from language-specific lists (`Dr.`, `Prof.`, `etc.`, etc.)
232
+ - Matched against custom abbreviations specified via `--slw-abbreviations`
233
+ - Part of user-specified suppression words via `--slw-suppressions`
234
+ 1. Abbreviation matching is case-insensitive by default (use `--slw-case-sensitive` to change)
235
+
236
+ ### Algorithm
237
+
238
+ 1. Insert a line break after every character that ends a sentence which complies with the above rules and exceptions
239
+ 1. Collapse all consecutive whitespace into a single space. While doing so, preserve both non-breaking spaces and linebreaks that are preceded by non-breaking spaces
240
+ 1. Before line wrapping, replace all spaces in link texts by non-breaking spaces (and similar inline content that can't be wrapped)
241
+ 1. Wrap lines that are longer than the maximum line width, if set, (80 characters by default) without splitting words or splitting at non-breaking spaces while also keeping indents in tact.
242
+
243
+ ## Acknowledgments
244
+
245
+ This plugin is inspired by and named after [mdslw](https://github.com/razziel89/mdslw) by [@razziel89](https://github.com/razziel89). The original `mdslw` is an excellent standalone tool for semantic line wrapping of markdown files.
246
+
247
+ **Why create mdformat-slw?**
248
+
249
+ The [mdformat](https://github.com/executablebooks/mdformat) ecosystem uses a plugin architecture where formatters must integrate with mdformat's AST-based processing pipeline. While `mdslw` works great as a standalone tool, it cannot be used as an mdformat plugin directly. This plugin reimplements semantic line wrapping concepts to work natively within mdformat, enabling:
250
+
251
+ - Seamless integration with other mdformat plugins
252
+ - Consistent formatting when mdformat is your primary markdown formatter
253
+ - Use in pre-commit hooks alongside mdformat's other capabilities
254
+
255
+ The plugin is named `slw` (not `mdslw`) to clearly distinguish it from the original tool and avoid confusion, since the implementations differ.
256
+
257
+ ## Contributing
258
+
259
+ See [CONTRIBUTING.md](https://github.com/kyleking/mdformat-slw/blob/main/CONTRIBUTING.md)
260
+
261
+ [ci-badge]: https://github.com/kyleking/mdformat-slw/actions/workflows/tests.yml/badge.svg?branch=main
262
+ [ci-link]: https://github.com/kyleking/mdformat-slw/actions?query=workflow%3ACI+branch%3Amain+event%3Apush
263
+ [pypi-badge]: https://img.shields.io/pypi/v/mdformat-slw.svg
264
+ [pypi-link]: https://pypi.org/project/mdformat-slw
@@ -0,0 +1,11 @@
1
+ mdformat_slw/__init__.py,sha256=lefvVyNaKMw3VkT5D6IuVcMST8iH_YzeyFGi67lYGGk,440
2
+ mdformat_slw/_helpers.py,sha256=07TvHXf4xdRPsbJAnkHXMlVKvb43e1tVdg5Mz_WxOsQ,962
3
+ mdformat_slw/_language_data.py,sha256=iAGN6HouQp5UZlMYRqJqlT5y5QfRq8n4JVZ-6D4IA9Q,2545
4
+ mdformat_slw/_sentence_wrapper.py,sha256=9HMJBVJxqMEclNxYUWosjNtWMM3HcQ4OL4lW5kU9fw8,19427
5
+ mdformat_slw/plugin.py,sha256=KF_f9QLoGCF-iiS9T0DzF6klua3XBy-5c7BzI9e92sw,4159
6
+ mdformat_slw/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ mdformat_slw-0.2.0.dist-info/licenses/LICENSE,sha256=Ot-rD8H1f8H88Mlt-QtxFZ-Fo75Oy3QtkCywrlU0X-w,1066
8
+ mdformat_slw-0.2.0.dist-info/WHEEL,sha256=3id4o64OvRm9dUknh3mMJNcfoTRK08ua5cU6DFyVy-4,79
9
+ mdformat_slw-0.2.0.dist-info/entry_points.txt,sha256=H9lSyZrvqtsbwSC1asmSfW2wZPohkwAkLJ4S_MyeaAE,48
10
+ mdformat_slw-0.2.0.dist-info/METADATA,sha256=qfMDq7ucbVmjRfe229TjbMAJRK4sZH79Uoqv_gANwyk,8641
11
+ mdformat_slw-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.9.13
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [mdformat.parser_extension]
2
+ slw = mdformat_slw
3
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Kyle King
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.