From 79dd20da48c9f5037bcd59150a0d4cd85ea134af Mon Sep 17 00:00:00 2001 From: Val Neekman Date: Mon, 16 Nov 2026 14:32:37 -0500 Subject: [PATCH 1/5] Keep combining marks and in-word joiners in modern Unicode slugs (#214) --- CHANGELOG.md | 4 ++ README.md | 2 +- slugify/slugify.py | 49 ++++++++++++++++++-- tests/test_modern_combining_marks.py | 69 ++++++++++++++++++++++++++++ 4 files changed, 120 insertions(+), 4 deletions(-) create mode 100644 tests/test_modern_combining_marks.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 8286871..630f53a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +## Unreleased + +- Modern mode only: with `allow_unicode=True`, keep combining marks (Unicode Mn/Mc, e.g. vowel signs, viramas, Arabic harakat, Hebrew niqqud) and in-word ZWNJ/ZWJ as part of words instead of splitting at them, fixing slugs for Hindi, Tamil, Bengali, Sinhala, Thai, Khmer, Myanmar, Arabic, Hebrew and other scripts. Output is unchanged for text without combining marks or joiners. Legacy output is unchanged (Nipuna-Lakruwan, #214). + ## 9.1.3 - Modern mode only: preserve repeated and leading post-replacement delimiters during word-boundary truncation, instead of collapsing them to a single separator. Legacy output and public `smart_truncate` are unchanged (aarush, #204). diff --git a/README.md b/README.md index 41480be..4332203 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,7 @@ slugify( - `lowercase`: apply `str.lower()`; false preserves case. - `replacements`: ordered iterable of `(old, new)` literal string rules. Legacy preserves iterator consumption across passes. Modern materializes outer and inner iterables once so generators behave like lists. - `replacement_stage`: `both` preserves two passes; `pre` runs only before normalization; `post` runs after cleanup and stopword removal, before separator mapping and truncation. Post replacements are **not** re-sanitized. Replacements need not be idempotent. -- `allow_unicode`: retain Unicode word characters after NFKC normalization, not exact original code points; default ASCII mode uses NFKD plus transliteration. +- `allow_unicode`: retain Unicode word characters after NFKC normalization, not exact original code points; default ASCII mode uses NFKD plus transliteration. Modern mode also keeps combining marks (vowel signs, viramas, harakat, niqqud) and in-word ZWNJ/ZWJ inside words, so `'नमस्ते दुनिया'` becomes `'नमस्ते-दुनिया'`; legacy splits words at those marks. - `backend`: select a backend from the table above. Ignored for transliteration in Unicode mode, but still validated. `smart_truncate(string, max_length=0, word_boundary=False, separator=' ', save_order=False)` diff --git a/slugify/slugify.py b/slugify/slugify.py index 27df54b..ddbf807 100644 --- a/slugify/slugify.py +++ b/slugify/slugify.py @@ -21,6 +21,12 @@ DUPLICATE_DASH_PATTERN = re.compile(r'-{2,}') NUMBERS_PATTERN = re.compile(r'(?<=\d),(?=\d)') DEFAULT_SEPARATOR = '-' +# Zero-width non-joiner/joiner: spelling-significant inside words in Indic, +# Sinhala and Persian text (e.g. Sinhala "ශ්‍රී"), invisible noise elsewhere. +WORD_JOINERS = frozenset('\u200c\u200d') +# Python's \w excludes nonspacing/spacing combining marks (Mn/Mc), which split +# Devanagari, Tamil, Bengali, Thai, Arabic, Hebrew, etc. words apart. +COMBINING_MARK_CATEGORIES = frozenset(('Mn', 'Mc')) Backend = Literal['auto', 'text-unidecode', 'unidecode', 'anyascii'] ReplacementStage = Literal['both', 'pre', 'post'] @@ -66,6 +72,38 @@ def _transliterate(text: str, backend: Backend) -> str: return result +def _is_combining_mark(char: str) -> bool: + # Variation selectors are Mn but select emoji/glyph styles, not spelling. + if '\ufe00' <= char <= '\ufe0f' or '\U000e0100' <= char <= '\U000e01ef': + return False + return unicodedata.category(char) in COMBINING_MARK_CATEGORIES + + +def _replace_disallowed_unicode(text: str) -> str: + """Modern Unicode-mode filter: [\\W_]+ -> '-', but keep words whole. + + A combining mark is a word character when it continues a word; a ZWNJ/ZWJ + is kept only between word parts. Identical to the plain [\\W_]+ filter + for text without combining marks or joiners. + """ + chars: list[str] = [] + in_word = False + last = len(text) - 1 + for index, char in enumerate(text): + if char.isalnum(): # Same definition as str-pattern \w, minus '_'. + in_word = True + elif in_word and _is_combining_mark(char): + pass + elif in_word and char in WORD_JOINERS and index < last and ( + text[index + 1].isalnum() or _is_combining_mark(text[index + 1])): + pass + else: + in_word = False + char = DEFAULT_SEPARATOR + chars.append(char) + return ''.join(chars) + + def _modern_truncate(text: str, max_length: int, word_boundary: bool, separator: str, save_order: bool) -> str: """Budget internal dash-separated tokens before mapping output delimiters. @@ -111,7 +149,8 @@ def _modern_truncate(text: str, max_length: int, word_boundary: bool, separator: remaining = max_length - length - len(delimiter) if remaining <= 0: break - parts.append(delimiter + word[:remaining]) + # A cut must not leave an invisible joiner dangling at the end. + parts.append(delimiter + word[:remaining].rstrip(''.join(WORD_JOINERS))) length += len(delimiter) + min(len(word), remaining) previous_index = index if len(word) > remaining: @@ -168,8 +207,12 @@ def _modern_slugify( text = text.lower() text = QUOTE_PATTERN.sub('', text) text = NUMBERS_PATTERN.sub('', text) - pattern = regex_pattern or (DISALLOWED_UNICODE_CHARS_PATTERN if allow_unicode else DISALLOWED_CHARS_PATTERN) - text = re.sub(pattern, DEFAULT_SEPARATOR, text) + if regex_pattern: + text = re.sub(regex_pattern, DEFAULT_SEPARATOR, text) + elif allow_unicode: + text = _replace_disallowed_unicode(text) + else: + text = DISALLOWED_CHARS_PATTERN.sub(DEFAULT_SEPARATOR, text) text = DUPLICATE_DASH_PATTERN.sub(DEFAULT_SEPARATOR, text).strip(DEFAULT_SEPARATOR) if stopwords: diff --git a/tests/test_modern_combining_marks.py b/tests/test_modern_combining_marks.py new file mode 100644 index 0000000..676aad1 --- /dev/null +++ b/tests/test_modern_combining_marks.py @@ -0,0 +1,69 @@ +import re +import unicodedata +import unittest + +from slugify import slugify +from slugify.slugify import _replace_disallowed_unicode + + +def modern(text, **kwargs): + return slugify(text, allow_unicode=True, algorithm='modern', **kwargs) + + +class ModernCombiningMarkTests(unittest.TestCase): + """Issue #214: combining marks and joiners must not split Unicode words.""" + + def test_scripts_with_combining_marks_stay_whole(self): + cases = ( + ('नमस्ते दुनिया', 'नमस्ते-दुनिया'), # Hindi + ('தமிழ் மொழி', 'தமிழ்-மொழி'), # Tamil + ('বাংলা ভাষা', 'বাংলা-ভাষা'), # Bengali + ('ਪੰਜਾਬੀ ਭਾਸ਼ਾ', 'ਪੰਜਾਬੀ-ਭਾਸ਼ਾ'), # Gurmukhi + ('తెలుగు భాష', 'తెలుగు-భాష'), # Telugu + ('ภาษาไทย ดี', 'ภาษาไทย-ดี'), # Thai + ('ភាសាខ្មែរ', 'ភាសាខ្មែរ'), # Khmer + ('မြန်မာစာ', 'မြန်မာစာ'), # Myanmar + ('مَرْحَبًا بِكُمْ', 'مَرْحَبًا-بِكُمْ'), # Arabic with harakat + ('שָׁלוֹם עוֹלָם', 'שָׁלוֹם-עוֹלָם'), # Hebrew with niqqud + ('ජනාධිපතිවරයා පාර්ලිමේන්තුවට ගියේය', + 'ජනාධිපතිවරයා-පාර්ලිමේන්තුවට-ගියේය'), # Sinhala + ) + for text, expected in cases: + with self.subTest(text=text): + self.assertEqual(modern(text), unicodedata.normalize('NFKC', expected)) + + def test_joiners_are_kept_only_inside_words(self): + self.assertEqual(modern('ශ්\u200dරී ලංකාව'), 'ශ්\u200dරී-ලංකාව') # Sinhala ZWJ + self.assertEqual(modern('می\u200cخواهم'), 'می\u200cخواهم') # Persian ZWNJ + for text in ('\u200dabc', 'abc\u200d', 'a \u200d b', 'a\u200d\u200db', 'a\u200d-b'): + with self.subTest(text=repr(text)): + self.assertNotIn('\u200d', modern(text)) + + def test_marks_without_a_base_and_emoji_selectors_are_separators(self): + self.assertEqual(modern('\u094dक'), 'क') # Leading orphan virama. + self.assertEqual(modern('a \u0301 b'), 'a-b') + self.assertEqual(modern('1\ufe0f\u20e3 go'), '1-go') # Keycap emoji. + + def test_hard_cut_does_not_end_with_a_joiner(self): + self.assertEqual(modern('ශ්\u200dරී', max_length=2), 'ශ්') + + def test_legacy_default_is_unchanged(self): + self.assertEqual(slugify('नमस्ते दुनिया', allow_unicode=True), 'नमस-त-द-न-य') + + def test_custom_regex_pattern_is_unchanged(self): + self.assertEqual(modern('नमस्ते', regex_pattern=r'[\W_]+'), 'नमस-त') + + def test_identical_to_plain_filter_without_marks_or_joiners(self): + old = re.compile(r'[\W_]+') + checked = 0 + for code in range(0x110000): + char = chr(code) + if 0xD800 <= code <= 0xDFFF or char in '\u200c\u200d': + continue + if unicodedata.category(char) in ('Mn', 'Mc'): + continue + for text in (char, 'a' + char + 'b', char + char): + new = re.sub('-{2,}', '-', _replace_disallowed_unicode(text)) + self.assertEqual(new, re.sub('-{2,}', '-', old.sub('-', text)), hex(code)) + checked += 1 + self.assertGreater(checked, 1_000_000) From 2e5a8bfad7f337ae83cdd9cd24eb68e93d6dbcce Mon Sep 17 00:00:00 2001 From: Val Neekman Date: Mon, 16 Nov 2026 14:35:29 -0500 Subject: [PATCH 2/5] Keep the regex fast path for ASCII input in modern Unicode mode (#214) --- slugify/slugify.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/slugify/slugify.py b/slugify/slugify.py index ddbf807..2ee66a5 100644 --- a/slugify/slugify.py +++ b/slugify/slugify.py @@ -86,6 +86,8 @@ def _replace_disallowed_unicode(text: str) -> str: is kept only between word parts. Identical to the plain [\\W_]+ filter for text without combining marks or joiners. """ + if text.isascii(): # No marks or joiners possible: keep the fast C regex path. + return DISALLOWED_UNICODE_CHARS_PATTERN.sub(DEFAULT_SEPARATOR, text) chars: list[str] = [] in_word = False last = len(text) - 1 From e907017d56871ac095d0d88d01e49cce179df777 Mon Sep 17 00:00:00 2001 From: Val Neekman Date: Mon, 16 Nov 2026 14:35:29 -0500 Subject: [PATCH 3/5] Release 9.2.0: keep combining marks and in-word joiners in modern Unicode slugs (#214) Credit Nipuna-Lakruwan, #214. --- CHANGELOG.md | 2 +- slugify/__version__.py | 2 +- tools/check_dist.py | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 630f53a..81e1734 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,4 @@ -## Unreleased +## 9.2.0 - Modern mode only: with `allow_unicode=True`, keep combining marks (Unicode Mn/Mc, e.g. vowel signs, viramas, Arabic harakat, Hebrew niqqud) and in-word ZWNJ/ZWJ as part of words instead of splitting at them, fixing slugs for Hindi, Tamil, Bengali, Sinhala, Thai, Khmer, Myanmar, Arabic, Hebrew and other scripts. Output is unchanged for text without combining marks or joiners. Legacy output is unchanged (Nipuna-Lakruwan, #214). diff --git a/slugify/__version__.py b/slugify/__version__.py index af26b6f..5de4cb3 100644 --- a/slugify/__version__.py +++ b/slugify/__version__.py @@ -5,4 +5,4 @@ __url__ = 'https://github.com/un33k/python-slugify' __license__ = 'SPDX-License-Identifier: MIT' __copyright__ = 'Copyright 2022 Val Neekman @ Neekware Inc.' -__version__ = '9.1.3' +__version__ = '9.2.0' diff --git a/tools/check_dist.py b/tools/check_dist.py index f2907dd..b53fff4 100644 --- a/tools/check_dist.py +++ b/tools/check_dist.py @@ -21,7 +21,7 @@ def run(*args, cwd=ROOT): def check_metadata(raw): metadata = email.message_from_bytes(raw) assert metadata['Name'] == 'python-slugify' - assert metadata['Version'] == '9.1.3' + assert metadata['Version'] == '9.2.0' assert metadata['Requires-Python'] == '>=3.10' assert metadata['License-Expression'] == 'MIT' assert set(metadata.get_all('Provides-Extra')) == {'unidecode', 'anyascii'} @@ -77,7 +77,7 @@ def main(): run(python, '-m', 'pip', 'install', '--disable-pip-version-check', artifact, cwd=scratch) run(python, '-m', 'pip', 'check', cwd=scratch) run(python, '-c', "import slugify; from importlib.metadata import version; " - "assert version('python-slugify') == slugify.__version__ == '9.1.3'; " + "assert version('python-slugify') == slugify.__version__ == '9.2.0'; " "assert slugify.slugify('影師嗎', backend='text-unidecode') == 'ying-shi-ma'; " "print(slugify.__file__)", cwd=scratch) # Execute copied API checks outside the checkout, importing only installed code. From cc9534cf8e0bf2e34e8e875d21f3cf47e8a09d5a Mon Sep 17 00:00:00 2001 From: Val Neekman Date: Mon, 16 Nov 2026 14:46:35 -0500 Subject: [PATCH 4/5] Make the Unicode equivalence test cheap under PyPy coverage (#214) --- tests/test_modern_combining_marks.py | 31 ++++++++++++++++------------ 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/tests/test_modern_combining_marks.py b/tests/test_modern_combining_marks.py index 676aad1..b1c5900 100644 --- a/tests/test_modern_combining_marks.py +++ b/tests/test_modern_combining_marks.py @@ -54,16 +54,21 @@ def test_custom_regex_pattern_is_unchanged(self): self.assertEqual(modern('नमस्ते', regex_pattern=r'[\W_]+'), 'नमस-त') def test_identical_to_plain_filter_without_marks_or_joiners(self): - old = re.compile(r'[\W_]+') - checked = 0 - for code in range(0x110000): - char = chr(code) - if 0xD800 <= code <= 0xDFFF or char in '\u200c\u200d': - continue - if unicodedata.category(char) in ('Mn', 'Mc'): - continue - for text in (char, 'a' + char + 'b', char + char): - new = re.sub('-{2,}', '-', _replace_disallowed_unicode(text)) - self.assertEqual(new, re.sub('-{2,}', '-', old.sub('-', text)), hex(code)) - checked += 1 - self.assertGreater(checked, 1_000_000) + # Outside marks/joiners the filter keeps exactly str.isalnum() chars, so + # equivalence reduces to: [^\W_] == isalnum for every code point. Checked + # in bulk, without per-character calls into traced code (PyPy + coverage). + everything = ''.join(chr(code) for code in range(0x110000) + if not 0xD800 <= code <= 0xDFFF) + self.assertEqual(''.join(re.findall(r'[^\W_]', everything)), + ''.join(filter(str.isalnum, everything))) + # And the filter itself, on a sample covering every general category. + sample: dict = {} + for char in everything[::7]: + chars = sample.setdefault(unicodedata.category(char), []) + if len(chars) < 40 and char not in '\u200c\u200d': + chars.append(char) + sample.pop('Mn', None) + sample.pop('Mc', None) + text = ''.join(char for chars in sample.values() for char in chars) + self.assertGreater(len(set(map(unicodedata.category, text))), 25) + self.assertEqual(_replace_disallowed_unicode(text), re.sub(r'[\W_]', '-', text)) From 59fc17a38a27de84f0e825693e75be17aa38ff39 Mon Sep 17 00:00:00 2001 From: Val Neekman Date: Mon, 16 Nov 2026 14:46:35 -0500 Subject: [PATCH 5/5] CI: run tox environments in parallel --- .github/workflows/main.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index ba50793..9aa0c08 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -26,8 +26,9 @@ jobs: run: | python -m pip install coveralls tox tox-uv - name: Run test + # Parallel envs; tox still honors depends (erase -> tests -> report). run: | - tox + tox run-parallel --parallel auto --parallel-no-spinner - name: Coveralls run: coveralls --service=github env: