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: diff --git a/CHANGELOG.md b/CHANGELOG.md index 8286871..81e1734 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +## 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). + ## 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/__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/slugify/slugify.py b/slugify/slugify.py index 27df54b..2ee66a5 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,40 @@ 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. + """ + 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 + 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 +151,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 +209,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..b1c5900 --- /dev/null +++ b/tests/test_modern_combining_marks.py @@ -0,0 +1,74 @@ +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): + # 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)) 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.