| 1 |
|
| 2 |
e. |
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
"""(Re)generate the utils.punctuation_chars module. |
| 17 |
|
| 18 |
The category of some characters can change with the development of the |
| 19 |
Unicode standard. This tool checks the patterns in `utils.punctuation_chars` |
| 20 |
against a re-calculation based on the "unicodedata" stdlib module |
| 21 |
which may give different results for different Python versions. |
| 22 |
|
| 23 |
.. admonition:: API change |
| 24 |
|
| 25 |
Updating the module with changed `unicode_punctuation_categories` |
| 26 |
(due to a new Python or Unicode standard version is an API change |
| 27 |
(may render valid rST documents invalid). It should only be done for |
| 28 |
"feature releases" and requires also updating the specification of |
| 29 |
`inline markup recognition rules`_. |
| 30 |
|
| 31 |
.. _inline markup recognition rules: |
| 32 |
https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html |
| 33 |
#inline-markup-recognition-rules |
| 34 |
""" |
| 35 |
|
| 36 |
from __future__ import annotations |
| 37 |
|
| 38 |
import sys |
| 39 |
import unicodedata |
| 40 |
|
| 41 |
TYPE_CHECKING = False |
| 42 |
if TYPE_CHECKING: |
| 43 |
from collections.abc import Iterable |
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
module_template = r'''# :Id: $Id: generate_punctuation_chars.py 10045 2025-03-09 01:02:23Z aa-turner $ |
| 50 |
# :Copyright: © 2011, 2017, 2022 Günter Milde. |
| 51 |
# :License: Released under the terms of the `2-Clause BSD license`_, in short: |
| 52 |
# |
| 53 |
# Copying and distribution of this file, with or without modification, |
| 54 |
# are permitted in any medium without royalty provided the copyright |
| 55 |
# notice and this notice are preserved. |
| 56 |
# This file is offered as-is, without any warranty. |
| 57 |
# |
| 58 |
# .. _2-Clause BSD license: https://opensource.org/licenses/BSD-2-Clause |
| 59 |
# |
| 60 |
# This file is generated by |
| 61 |
# ``docutils/tools/dev/generate_punctuation_chars.py``. |
| 62 |
# :: |
| 63 |
|
| 64 |
"""Docutils character category patterns. |
| 65 |
|
| 66 |
Patterns for the implementation of the `inline markup recognition rules`_ |
| 67 |
in the reStructuredText parser `docutils.parsers.rst.states.py` based |
| 68 |
on Unicode character categories. |
| 69 |
The patterns are used inside ``[ ]`` in regular expressions. |
| 70 |
|
| 71 |
Rule (5) requires determination of matching open/close pairs. However, the |
| 72 |
pairing of open/close quotes is ambiguous due to different typographic |
| 73 |
conventions in different languages. The ``quote_pairs`` function tests |
| 74 |
whether two characters form an open/close pair. |
| 75 |
|
| 76 |
The patterns are generated by |
| 77 |
``docutils/tools/dev/generate_punctuation_chars.py`` to prevent dependence |
| 78 |
on the Python version and avoid the time-consuming generation with every |
| 79 |
Docutils run. See there for motives and implementation details. |
| 80 |
|
| 81 |
The category of some characters changed with the development of the |
| 82 |
Unicode standard. The current lists are generated with the help of the |
| 83 |
"unicodedata" module of Python %(python_version)s (based on Unicode version %(unidata_version)s). |
| 84 |
|
| 85 |
.. _inline markup recognition rules: |
| 86 |
https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html |
| 87 |
#inline-markup-recognition-rules |
| 88 |
""" # noqa: E501 |
| 89 |
|
| 90 |
%(openers)s |
| 91 |
%(closers)s |
| 92 |
%(delimiters)s |
| 93 |
closing_delimiters = r'\\.,;!?' |
| 94 |
|
| 95 |
|
| 96 |
# Matching open/close quotes |
| 97 |
# -------------------------- |
| 98 |
|
| 99 |
# Matching open/close pairs are at the same position in |
| 100 |
# `punctuation_chars.openers` and `punctuation_chars.closers`. |
| 101 |
# Additional matches (due to different typographic conventions |
| 102 |
# in different languages) are stored in `quote_pairs`. |
| 103 |
|
| 104 |
quote_pairs = { |
| 105 |
# open char: matching closing characters # use case |
| 106 |
'\xbb': '\xbb', # » » Swedish |
| 107 |
'\u2018': '\u201a', # ‘ ‚ Albanian/Greek/Turkish |
| 108 |
'\u2019': '\u2019', # ’ ’ Swedish |
| 109 |
'\u201a': '\u2018\u2019', # ‚ ‘ German, ‚ ’ Polish |
| 110 |
'\u201c': '\u201e', # “ „ Albanian/Greek/Turkish |
| 111 |
'\u201e': '\u201c\u201d', # „ “ German, „ ” Polish |
| 112 |
'\u201d': '\u201d', # ” ” Swedish |
| 113 |
'\u203a': '\u203a', # › › Swedish |
| 114 |
'\u301d': '\u301f' # 〝 〟 CJK punctuation |
| 115 |
'\u2e42': '\u201F', # ⹂ ‟ Old Hungarian (right to left) |
| 116 |
} |
| 117 |
"""Additional open/close quote pairs.""" |
| 118 |
|
| 119 |
|
| 120 |
def match_chars(c1, c2): |
| 121 |
"""Test whether `c1` and `c2` are a matching open/close character pair.""" |
| 122 |
try: |
| 123 |
i = openers.index(c1) |
| 124 |
except ValueError: # c1 not in openers |
| 125 |
return False |
| 126 |
return c2 == closers[i] or c2 in quote_pairs.get(c1, '') |
| 127 |
''' |
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
unicode_punctuation_categories = { |
| 141 |
'Pd': 'dash', |
| 142 |
'Ps': 'open', |
| 143 |
'Pe': 'close', |
| 144 |
'Pi': 'initial quote', |
| 145 |
'Pf': 'final quote', |
| 146 |
'Po': 'other' |
| 147 |
} |
| 148 |
"""Unicode character categories for punctuation""" |
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
def unicode_charlists(categories: Iterable[str], |
| 157 |
cp_min: int = 0, |
| 158 |
cp_max: int = sys.maxunicode, |
| 159 |
) -> dict[str, list[str]]: |
| 160 |
"""Return dictionary of Unicode character lists. |
| 161 |
|
| 162 |
For each of the `catagories`, an item contains a list with all Unicode |
| 163 |
characters with `cp_min` <= code-point <= `cp_max` that belong to |
| 164 |
the category. |
| 165 |
""" |
| 166 |
char_lists = {cat: [] for cat in categories} |
| 167 |
for i in range(cp_min, cp_max+1): |
| 168 |
chr_i = chr(i) |
| 169 |
cat_i = unicodedata.category(chr_i) |
| 170 |
if cat_i in char_lists: |
| 171 |
char_lists[cat_i].append(chr_i) |
| 172 |
return char_lists |
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
def character_category_patterns() -> tuple[str, str, str, str]: |
| 181 |
|
| 182 |
"""Docutils character category patterns. |
| 183 |
|
| 184 |
Return list of pattern strings for the categories "Open", "Close", |
| 185 |
"Delimiters" and "Closing-Delimiters" used in the `inline markup |
| 186 |
recognition rules`_. |
| 187 |
""" |
| 188 |
|
| 189 |
cp_min = 160 |
| 190 |
ucharlists = unicode_charlists(unicode_punctuation_categories, cp_min) |
| 191 |
"""Strings of characters in Unicode punctuation character categories""" |
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
ucharlists['Ps'].remove('‚')RK |
| 202 |
ucharlists['Ps'].remove('„')RK |
| 203 |
|
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
ucharlists['Pf'].insert(ucharlists['Pi'].index('‛'), '‚') |
| 208 |
ucharlists['Pf'].insert(ucharlists['Pi'].index('‟'), '„') |
| 209 |
|
| 210 |
RK |
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
|
| 216 |
RK |
| 217 |
|
| 218 |
|
| 219 |
ucharlists['Pe'].remove('\u301f') |
| 220 |
ucharlists['Pe'].insert(ucharlists['Ps'].index('⹂'), '\u301f') |
| 221 |
|
| 222 |
|
| 223 |
if len(ucharlists['Ps']) != len(ucharlists['Pe']): |
| 224 |
print('Missmatch between "Open" and "Close" categories') |
| 225 |
print(''.join(ucharlists['Ps'])) |
| 226 |
print(''.join(ucharlists['Pe'])) |
| 227 |
raise AssertionError |
| 228 |
if len(ucharlists['Pi']) != len(ucharlists['Pf']): |
| 229 |
print('Missmatch between "initial quote" and "final quote" categories') |
| 230 |
print(''.join(ucharlists['Pi'])) |
| 231 |
print(''.join(ucharlists['Pf'])) |
| 232 |
raise AssertionError |
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
openers = ['"\'(<\\[{'] |
| 243 |
for category in ('Ps', 'Pi', 'Pf'): |
| 244 |
openers.extend(ucharlists[category]) |
| 245 |
|
| 246 |
|
| 247 |
closers = ['"\')>\\]}'] |
| 248 |
for category in ('Pe', 'Pf', 'Pi'): |
| 249 |
closers.extend(ucharlists[category]) |
| 250 |
|
| 251 |
|
| 252 |
delimiters = [r'\-/:'] |
| 253 |
for category in ('Pd', 'Po'): |
| 254 |
delimiters.extend(ucharlists[category]) |
| 255 |
|
| 256 |
|
| 257 |
closing_delimiters = [r'\\.,;!?'] |
| 258 |
|
| 259 |
return tuple(''.join(chs) |
| 260 |
for chs in (openers, closers, delimiters, closing_delimiters)) |
| 261 |
|
| 262 |
|
| 263 |
def mark_intervals(s: str) -> str: |
| 264 |
"""Return s with shortcut notation for runs of consecutive characters |
| 265 |
|
| 266 |
Sort string and replace 'cdef' by 'c-f' and similar. |
| 267 |
""" |
| 268 |
lst: list[list[int]] = [] |
| 269 |
s = sorted(ord(ch) for ch in s) |
| 270 |
for n in s: |
| 271 |
try: |
| 272 |
if lst[-1][-1] + 1 == n: |
| 273 |
lst[-1].append(n) |
| 274 |
else: |
| 275 |
lst.append([n]) |
| 276 |
except IndexError: |
| 277 |
lst.append([n]) |
| 278 |
|
| 279 |
lst2: list[str] = [] |
| 280 |
for i in lst: |
| 281 |
i = [chr(n) for n in i] |
| 282 |
if len(i) > 2: |
| 283 |
i = i[0], '-', i[-1] |
| 284 |
lst2.extend(i) |
| 285 |
|
| 286 |
return ''.join(lst2) |
| 287 |
|
| 288 |
|
| 289 |
def wrap_string( |
| 290 |
s: str, |
| 291 |
startstring: str = "(", |
| 292 |
endstring: str = " )", |
| 293 |
wrap: int = 71, |
| 294 |
) -> str: |
| 295 |
"""Line-wrap a unicode string literal definition.""" |
| 296 |
s = s.encode('unicode-escape').decode() |
| 297 |
c = len(startstring) |
| 298 |
left_indent = ' '*(c - len(startstring.lstrip(' '))) |
| 299 |
line_start_string = f"\n {left_indent}'" |
| 300 |
cont_string = f"'{line_start_string}" |
| 301 |
lst = [startstring, line_start_string] |
| 302 |
for ch in s.replace("'", r"\'"): |
| 303 |
c += 1 |
| 304 |
if ch == '\\' and c > wrap: |
| 305 |
c = len(startstring) |
| 306 |
lst.append(cont_string) |
| 307 |
lst.append(ch) |
| 308 |
lst.append(f"'\n{left_indent}{endstring}") |
| 309 |
return ''.join(lst) |
| 310 |
|
| 311 |
|
| 312 |
def print_differences(old: str, new: str, name: str) -> bool: |
| 313 |
"""List characters missing in old/new.""" |
| 314 |
if old != new: |
| 315 |
print(f'"{name}" changed') |
| 316 |
if '-' in old or '-' in new: |
| 317 |
print('-', old) |
| 318 |
print('+', new) |
| 319 |
else: |
| 320 |
for c in new: |
| 321 |
if c not in old: |
| 322 |
print('+ %04x'%ord(c), c, unicodedata.name(c)) |
| 323 |
for c in old: |
| 324 |
if c not in new: |
| 325 |
print('- %04x'%ord(c), c, unicodedata.name(c)) |
| 326 |
return True |
| 327 |
else: |
| 328 |
print(f'"{name}" unchanged') |
| 329 |
return False |
| 330 |
|
| 331 |
|
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
|
| 337 |
if __name__ == '__main__': |
| 338 |
|
| 339 |
import argparse |
| 340 |
parser = argparse.ArgumentParser(description=__doc__) |
| 341 |
parser.add_argument('-t', '--test', action="store_true", |
| 342 |
help='test for changed character categories') |
| 343 |
parser.add_argument('--pairs', action="store_true", |
| 344 |
help='show openers/closers in human readable form') |
| 345 |
args = parser.parse_args() |
| 346 |
|
| 347 |
|
| 348 |
|
| 349 |
|
| 350 |
|
| 351 |
|
| 352 |
(o, c, d, cd) = character_category_patterns() |
| 353 |
|
| 354 |
|
| 355 |
|
| 356 |
|
| 357 |
|
| 358 |
d = d[:5] + mark_intervals(d[5:]) |
| 359 |
|
| 360 |
|
| 361 |
|
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
if args.test: |
| 368 |
|
| 369 |
sys.path.insert(0, '../../docutils') |
| 370 |
|
| 371 |
from docutils.utils.punctuation_chars import ( |
| 372 |
openers, closers, delimiters, closing_delimiters) |
| 373 |
|
| 374 |
print('Check for differences between the current `punctuation_chars`' |
| 375 |
' module\n and a regeneration based on Unicode version %s:' |
| 376 |
% unicodedata.unidata_version) |
| 377 |
|
| 378 |
delta_o = print_differences(openers, o, 'openers') |
| 379 |
delta_c = print_differences(closers, c, 'closers') |
| 380 |
print_differences(delimiters, d, 'delimiters') |
| 381 |
print_differences(closing_delimiters, cd, 'closing_delimiters') |
| 382 |
|
| 383 |
if delta_o or delta_c: |
| 384 |
print('\nChanges in "openers" and/or "closers",' |
| 385 |
'\nCheck open/close pairs with option "--pairs"!') |
| 386 |
sys.exit() |
| 387 |
|
| 388 |
|
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
|
| 393 |
|
| 394 |
|
| 395 |
if args.pairs: |
| 396 |
for o_i, c_i in zip(o, c): |
| 397 |
print(o_i, c_i, |
| 398 |
unicodedata.name(o_i), '\t', unicodedata.name(c_i)) |
| 399 |
sys.exit() |
| 400 |
|
| 401 |
|
| 402 |
|
| 403 |
|
| 404 |
|
| 405 |
|
| 406 |
|
| 407 |
|
| 408 |
|
| 409 |
substitutions: dict[str, str] = { |
| 410 |
'python_version': sys.version.split()[0], |
| 411 |
'unidata_version': unicodedata.unidata_version, |
| 412 |
'openers': wrap_string(o, startstring="openers = ("), |
| 413 |
'closers': wrap_string(c, startstring="closers = ("), |
| 414 |
'delimiters': wrap_string(d, startstring="delimiters = ("), |
| 415 |
} |
| 416 |
|
| 417 |
print(module_template % substitutions, end='') |