GNXSOFT.COM

This commit is contained in:
Iliyan Angelov
2025-09-26 00:15:37 +03:00
commit fe26b7cca4
16323 changed files with 2011881 additions and 0 deletions

View File

@@ -0,0 +1,29 @@
"""
Wcwidth module.
https://github.com/jquast/wcwidth
"""
# re-export all functions & definitions, even private ones, from top-level
# module path, to allow for 'from wcwidth import _private_func'. Of course,
# user beware that any _private function may disappear or change signature at
# any future version.
# local
from .wcwidth import ZERO_WIDTH # noqa
from .wcwidth import (WIDE_EASTASIAN,
VS16_NARROW_TO_WIDE,
wcwidth,
wcswidth,
_bisearch,
list_versions,
_wcmatch_version,
_wcversion_value)
# The __all__ attribute defines the items exported from statement,
# 'from wcwidth import *', but also to say, "This is the public API".
__all__ = ('wcwidth', 'wcswidth', 'list_versions')
# We also used pkg_resources to load unicode version tables from version.json,
# generated by bin/update-tables.py, but some environments are unable to
# import pkg_resources for one reason or another, yikes!
__version__ = '0.2.14'

View File

@@ -0,0 +1,103 @@
"""
Exports VS15_WIDE_TO_NARROW table keyed by supporting unicode version level.
This code generated by wcwidth/bin/update-tables.py on 2024-02-14 19:59:22 UTC.
"""
VS15_WIDE_TO_NARROW = {
'9.0.0': (
# Source: 9.0.0
# Date: 2023-02-01, 02:22:54 GMT
#
(0x0231a, 0x0231b,), # Watch ..Hourglass
(0x023e9, 0x023ec,), # Black Right-pointing Dou..Black Down-pointing Doub
(0x023f0, 0x023f0,), # Alarm Clock
(0x023f3, 0x023f3,), # Hourglass With Flowing Sand
(0x025fd, 0x025fe,), # White Medium Small Squar..Black Medium Small Squar
(0x02614, 0x02615,), # Umbrella With Rain Drops..Hot Beverage
(0x02648, 0x02653,), # Aries ..Pisces
(0x0267f, 0x0267f,), # Wheelchair Symbol
(0x02693, 0x02693,), # Anchor
(0x026a1, 0x026a1,), # High Voltage Sign
(0x026aa, 0x026ab,), # Medium White Circle ..Medium Black Circle
(0x026bd, 0x026be,), # Soccer Ball ..Baseball
(0x026c4, 0x026c5,), # Snowman Without Snow ..Sun Behind Cloud
(0x026ce, 0x026ce,), # Ophiuchus
(0x026d4, 0x026d4,), # No Entry
(0x026ea, 0x026ea,), # Church
(0x026f2, 0x026f3,), # Fountain ..Flag In Hole
(0x026f5, 0x026f5,), # Sailboat
(0x026fa, 0x026fa,), # Tent
(0x026fd, 0x026fd,), # Fuel Pump
(0x02705, 0x02705,), # White Heavy Check Mark
(0x0270a, 0x0270b,), # Raised Fist ..Raised Hand
(0x02728, 0x02728,), # Sparkles
(0x0274c, 0x0274c,), # Cross Mark
(0x0274e, 0x0274e,), # Negative Squared Cross Mark
(0x02753, 0x02755,), # Black Question Mark Orna..White Exclamation Mark O
(0x02757, 0x02757,), # Heavy Exclamation Mark Symbol
(0x02795, 0x02797,), # Heavy Plus Sign ..Heavy Division Sign
(0x027b0, 0x027b0,), # Curly Loop
(0x027bf, 0x027bf,), # Double Curly Loop
(0x02b1b, 0x02b1c,), # Black Large Square ..White Large Square
(0x02b50, 0x02b50,), # White Medium Star
(0x02b55, 0x02b55,), # Heavy Large Circle
(0x03030, 0x03030,), # Wavy Dash
(0x0303d, 0x0303d,), # Part Alternation Mark
(0x03297, 0x03297,), # Circled Ideograph Congratulation
(0x03299, 0x03299,), # Circled Ideograph Secret
(0x1f004, 0x1f004,), # Mahjong Tile Red Dragon
(0x1f202, 0x1f202,), # Squared Katakana Sa
(0x1f21a, 0x1f21a,), # Squared Cjk Unified Ideograph-7121
(0x1f22f, 0x1f22f,), # Squared Cjk Unified Ideograph-6307
(0x1f237, 0x1f237,), # Squared Cjk Unified Ideograph-6708
(0x1f30d, 0x1f30f,), # Earth Globe Europe-afric..Earth Globe Asia-austral
(0x1f315, 0x1f315,), # Full Moon Symbol
(0x1f31c, 0x1f31c,), # Last Quarter Moon With Face
(0x1f378, 0x1f378,), # Cocktail Glass
(0x1f393, 0x1f393,), # Graduation Cap
(0x1f3a7, 0x1f3a7,), # Headphone
(0x1f3ac, 0x1f3ae,), # Clapper Board ..Video Game
(0x1f3c2, 0x1f3c2,), # Snowboarder
(0x1f3c4, 0x1f3c4,), # Surfer
(0x1f3c6, 0x1f3c6,), # Trophy
(0x1f3ca, 0x1f3ca,), # Swimmer
(0x1f3e0, 0x1f3e0,), # House Building
(0x1f3ed, 0x1f3ed,), # Factory
(0x1f408, 0x1f408,), # Cat
(0x1f415, 0x1f415,), # Dog
(0x1f41f, 0x1f41f,), # Fish
(0x1f426, 0x1f426,), # Bird
(0x1f442, 0x1f442,), # Ear
(0x1f446, 0x1f449,), # White Up Pointing Backha..White Right Pointing Bac
(0x1f44d, 0x1f44e,), # Thumbs Up Sign ..Thumbs Down Sign
(0x1f453, 0x1f453,), # Eyeglasses
(0x1f46a, 0x1f46a,), # Family
(0x1f47d, 0x1f47d,), # Extraterrestrial Alien
(0x1f4a3, 0x1f4a3,), # Bomb
(0x1f4b0, 0x1f4b0,), # Money Bag
(0x1f4b3, 0x1f4b3,), # Credit Card
(0x1f4bb, 0x1f4bb,), # Personal Computer
(0x1f4bf, 0x1f4bf,), # Optical Disc
(0x1f4cb, 0x1f4cb,), # Clipboard
(0x1f4da, 0x1f4da,), # Books
(0x1f4df, 0x1f4df,), # Pager
(0x1f4e4, 0x1f4e6,), # Outbox Tray ..Package
(0x1f4ea, 0x1f4ed,), # Closed Mailbox With Lowe..Open Mailbox With Lowere
(0x1f4f7, 0x1f4f7,), # Camera
(0x1f4f9, 0x1f4fb,), # Video Camera ..Radio
(0x1f508, 0x1f508,), # Speaker
(0x1f50d, 0x1f50d,), # Left-pointing Magnifying Glass
(0x1f512, 0x1f513,), # Lock ..Open Lock
(0x1f550, 0x1f567,), # Clock Face One Oclock ..Clock Face Twelve-thirty
(0x1f610, 0x1f610,), # Neutral Face
(0x1f687, 0x1f687,), # Metro
(0x1f68d, 0x1f68d,), # Oncoming Bus
(0x1f691, 0x1f691,), # Ambulance
(0x1f694, 0x1f694,), # Oncoming Police Car
(0x1f698, 0x1f698,), # Oncoming Automobile
(0x1f6ad, 0x1f6ad,), # No Smoking Symbol
(0x1f6b2, 0x1f6b2,), # Bicycle
(0x1f6b9, 0x1f6ba,), # Mens Symbol ..Womens Symbol
(0x1f6bc, 0x1f6bc,), # Baby Symbol
),
}

View File

@@ -0,0 +1,125 @@
"""
Exports VS16_NARROW_TO_WIDE table keyed by supporting unicode version level.
This code generated by wcwidth/bin/update-tables.py on 2025-09-15 16:57:50 UTC.
"""
VS16_NARROW_TO_WIDE = {
'9.0.0': (
# Source: 9.0.0
# Date: 2025-01-30, 21:48:29 GMT
#
(0x00023, 0x00023,), # Number Sign
(0x0002a, 0x0002a,), # Asterisk
(0x00030, 0x00039,), # Digit Zero ..Digit Nine
(0x000a9, 0x000a9,), # Copyright Sign
(0x000ae, 0x000ae,), # Registered Sign
(0x0203c, 0x0203c,), # Double Exclamation Mark
(0x02049, 0x02049,), # Exclamation Question Mark
(0x02122, 0x02122,), # Trade Mark Sign
(0x02139, 0x02139,), # Information Source
(0x02194, 0x02199,), # Left Right Arrow ..South West Arrow
(0x021a9, 0x021aa,), # Leftwards Arrow With Hoo..Rightwards Arrow With Ho
(0x02328, 0x02328,), # Keyboard
(0x023cf, 0x023cf,), # Eject Symbol
(0x023ed, 0x023ef,), # Black Right-pointing Dou..Black Right-pointing Tri
(0x023f1, 0x023f2,), # Stopwatch ..Timer Clock
(0x023f8, 0x023fa,), # Double Vertical Bar ..Black Circle For Record
(0x024c2, 0x024c2,), # Circled Latin Capital Letter M
(0x025aa, 0x025ab,), # Black Small Square ..White Small Square
(0x025b6, 0x025b6,), # Black Right-pointing Triangle
(0x025c0, 0x025c0,), # Black Left-pointing Triangle
(0x025fb, 0x025fc,), # White Medium Square ..Black Medium Square
(0x02600, 0x02604,), # Black Sun With Rays ..Comet
(0x0260e, 0x0260e,), # Black Telephone
(0x02611, 0x02611,), # Ballot Box With Check
(0x02618, 0x02618,), # Shamrock
(0x0261d, 0x0261d,), # White Up Pointing Index
(0x02620, 0x02620,), # Skull And Crossbones
(0x02622, 0x02623,), # Radioactive Sign ..Biohazard Sign
(0x02626, 0x02626,), # Orthodox Cross
(0x0262a, 0x0262a,), # Star And Crescent
(0x0262e, 0x0262f,), # Peace Symbol ..Yin Yang
(0x02638, 0x0263a,), # Wheel Of Dharma ..White Smiling Face
(0x02640, 0x02640,), # Female Sign
(0x02642, 0x02642,), # Male Sign
(0x0265f, 0x02660,), # Black Chess Pawn ..Black Spade Suit
(0x02663, 0x02663,), # Black Club Suit
(0x02665, 0x02666,), # Black Heart Suit ..Black Diamond Suit
(0x02668, 0x02668,), # Hot Springs
(0x0267b, 0x0267b,), # Black Universal Recycling Symbol
(0x0267e, 0x0267e,), # Permanent Paper Sign
(0x02692, 0x02692,), # Hammer And Pick
(0x02694, 0x02697,), # Crossed Swords ..Alembic
(0x02699, 0x02699,), # Gear
(0x0269b, 0x0269c,), # Atom Symbol ..Fleur-de-lis
(0x026a0, 0x026a0,), # Warning Sign
(0x026a7, 0x026a7,), # Male With Stroke And Male And Female Sign
(0x026b0, 0x026b1,), # Coffin ..Funeral Urn
(0x026c8, 0x026c8,), # Thunder Cloud And Rain
(0x026cf, 0x026cf,), # Pick
(0x026d1, 0x026d1,), # Helmet With White Cross
(0x026d3, 0x026d3,), # Chains
(0x026e9, 0x026e9,), # Shinto Shrine
(0x026f0, 0x026f1,), # Mountain ..Umbrella On Ground
(0x026f4, 0x026f4,), # Ferry
(0x026f7, 0x026f9,), # Skier ..Person With Ball
(0x02702, 0x02702,), # Black Scissors
(0x02708, 0x02709,), # Airplane ..Envelope
(0x0270c, 0x0270d,), # Victory Hand ..Writing Hand
(0x0270f, 0x0270f,), # Pencil
(0x02712, 0x02712,), # Black Nib
(0x02714, 0x02714,), # Heavy Check Mark
(0x02716, 0x02716,), # Heavy Multiplication X
(0x0271d, 0x0271d,), # Latin Cross
(0x02721, 0x02721,), # Star Of David
(0x02733, 0x02734,), # Eight Spoked Asterisk ..Eight Pointed Black Star
(0x02744, 0x02744,), # Snowflake
(0x02747, 0x02747,), # Sparkle
(0x02763, 0x02764,), # Heavy Heart Exclamation ..Heavy Black Heart
(0x027a1, 0x027a1,), # Black Rightwards Arrow
(0x02934, 0x02935,), # Arrow Pointing Rightward..Arrow Pointing Rightward
(0x02b05, 0x02b07,), # Leftwards Black Arrow ..Downwards Black Arrow
(0x1f170, 0x1f171,), # Negative Squared Latin C..Negative Squared Latin C
(0x1f17e, 0x1f17f,), # Negative Squared Latin C..Negative Squared Latin C
(0x1f321, 0x1f321,), # Thermometer
(0x1f324, 0x1f32c,), # White Sun With Small Clo..Wind Blowing Face
(0x1f336, 0x1f336,), # Hot Pepper
(0x1f37d, 0x1f37d,), # Fork And Knife With Plate
(0x1f396, 0x1f397,), # Military Medal ..Reminder Ribbon
(0x1f399, 0x1f39b,), # Studio Microphone ..Control Knobs
(0x1f39e, 0x1f39f,), # Film Frames ..Admission Tickets
(0x1f3cb, 0x1f3ce,), # Weight Lifter ..Racing Car
(0x1f3d4, 0x1f3df,), # Snow Capped Mountain ..Stadium
(0x1f3f3, 0x1f3f3,), # Waving White Flag
(0x1f3f5, 0x1f3f5,), # Rosette
(0x1f3f7, 0x1f3f7,), # Label
(0x1f43f, 0x1f43f,), # Chipmunk
(0x1f441, 0x1f441,), # Eye
(0x1f4fd, 0x1f4fd,), # Film Projector
(0x1f549, 0x1f54a,), # Om Symbol ..Dove Of Peace
(0x1f56f, 0x1f570,), # Candle ..Mantelpiece Clock
(0x1f573, 0x1f579,), # Hole ..Joystick
(0x1f587, 0x1f587,), # Linked Paperclips
(0x1f58a, 0x1f58d,), # Lower Left Ballpoint Pen..Lower Left Crayon
(0x1f590, 0x1f590,), # Raised Hand With Fingers Splayed
(0x1f5a5, 0x1f5a5,), # Desktop Computer
(0x1f5a8, 0x1f5a8,), # Printer
(0x1f5b1, 0x1f5b2,), # Three Button Mouse ..Trackball
(0x1f5bc, 0x1f5bc,), # Frame With Picture
(0x1f5c2, 0x1f5c4,), # Card Index Dividers ..File Cabinet
(0x1f5d1, 0x1f5d3,), # Wastebasket ..Spiral Calendar Pad
(0x1f5dc, 0x1f5de,), # Compression ..Rolled-up Newspaper
(0x1f5e1, 0x1f5e1,), # Dagger Knife
(0x1f5e3, 0x1f5e3,), # Speaking Head In Silhouette
(0x1f5e8, 0x1f5e8,), # Left Speech Bubble
(0x1f5ef, 0x1f5ef,), # Right Anger Bubble
(0x1f5f3, 0x1f5f3,), # Ballot Box With Ballot
(0x1f5fa, 0x1f5fa,), # World Map
(0x1f6cb, 0x1f6cb,), # Couch And Lamp
(0x1f6cd, 0x1f6cf,), # Shopping Bags ..Bed
(0x1f6e0, 0x1f6e5,), # Hammer And Wrench ..Motor Boat
(0x1f6e9, 0x1f6e9,), # Small Airplane
(0x1f6f0, 0x1f6f0,), # Satellite
(0x1f6f3, 0x1f6f3,), # Passenger Ship
),
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,40 @@
"""
Exports function list_versions() for unicode version level support.
This code generated by wcwidth/bin/update-tables.py on 2025-09-15 16:57:50 UTC.
"""
def list_versions():
"""
Return Unicode version levels supported by this module release.
Any of the version strings returned may be used as keyword argument
``unicode_version`` to the ``wcwidth()`` family of functions.
:returns: Supported Unicode version numbers in ascending sorted order.
:rtype: list[str]
"""
return (
"4.1.0",
"5.0.0",
"5.1.0",
"5.2.0",
"6.0.0",
"6.1.0",
"6.2.0",
"6.3.0",
"7.0.0",
"8.0.0",
"9.0.0",
"10.0.0",
"11.0.0",
"12.0.0",
"12.1.0",
"13.0.0",
"14.0.0",
"15.0.0",
"15.1.0",
"16.0.0",
"17.0.0",
)

View File

@@ -0,0 +1,326 @@
"""
This is a python implementation of wcwidth() and wcswidth().
https://github.com/jquast/wcwidth
from Markus Kuhn's C code, retrieved from:
http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c
This is an implementation of wcwidth() and wcswidth() (defined in
IEEE Std 1002.1-2001) for Unicode.
http://www.opengroup.org/onlinepubs/007904975/functions/wcwidth.html
http://www.opengroup.org/onlinepubs/007904975/functions/wcswidth.html
In fixed-width output devices, Latin characters all occupy a single
"cell" position of equal width, whereas ideographic CJK characters
occupy two such cells. Interoperability between terminal-line
applications and (teletype-style) character terminals using the
UTF-8 encoding requires agreement on which character should advance
the cursor by how many cell positions. No established formal
standards exist at present on which Unicode character shall occupy
how many cell positions on character terminals. These routines are
a first attempt of defining such behavior based on simple rules
applied to data provided by the Unicode Consortium.
For some graphical characters, the Unicode standard explicitly
defines a character-cell width via the definition of the East Asian
FullWidth (F), Wide (W), Half-width (H), and Narrow (Na) classes.
In all these cases, there is no ambiguity about which width a
terminal shall use. For characters in the East Asian Ambiguous (A)
class, the width choice depends purely on a preference of backward
compatibility with either historic CJK or Western practice.
Choosing single-width for these characters is easy to justify as
the appropriate long-term solution, as the CJK practice of
displaying these characters as double-width comes from historic
implementation simplicity (8-bit encoded characters were displayed
single-width and 16-bit ones double-width, even for Greek,
Cyrillic, etc.) and not any typographic considerations.
Much less clear is the choice of width for the Not East Asian
(Neutral) class. Existing practice does not dictate a width for any
of these characters. It would nevertheless make sense
typographically to allocate two character cells to characters such
as for instance EM SPACE or VOLUME INTEGRAL, which cannot be
represented adequately with a single-width glyph. The following
routines at present merely assign a single-cell width to all
neutral characters, in the interest of simplicity. This is not
entirely satisfactory and should be reconsidered before
establishing a formal standard in this area. At the moment, the
decision which Not East Asian (Neutral) characters should be
represented by double-width glyphs cannot yet be answered by
applying a simple rule from the Unicode database content. Setting
up a proper standard for the behavior of UTF-8 character terminals
will require a careful analysis not only of each Unicode character,
but also of each presentation form, something the author of these
routines has avoided to do so far.
http://www.unicode.org/unicode/reports/tr11/
Latest version: http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c
"""
# std imports
import os
import warnings
from functools import lru_cache
# local
from .table_vs16 import VS16_NARROW_TO_WIDE
from .table_wide import WIDE_EASTASIAN
from .table_zero import ZERO_WIDTH
from .unicode_versions import list_versions
def _bisearch(ucs, table):
"""
Auxiliary function for binary search in interval table.
:arg int ucs: Ordinal value of unicode character.
:arg list table: List of starting and ending ranges of ordinal values,
in form of ``[(start, end), ...]``.
:rtype: int
:returns: 1 if ordinal value ucs is found within lookup table, else 0.
"""
lbound = 0
ubound = len(table) - 1
if ucs < table[0][0] or ucs > table[ubound][1]:
return 0
while ubound >= lbound:
mid = (lbound + ubound) // 2
if ucs > table[mid][1]:
lbound = mid + 1
elif ucs < table[mid][0]:
ubound = mid - 1
else:
return 1
return 0
@lru_cache(maxsize=1000)
def wcwidth(wc, unicode_version='auto'):
r"""
Given one Unicode character, return its printable length on a terminal.
:param str wc: A single Unicode character.
:param str unicode_version: A Unicode version number, such as
``'6.0.0'``. A list of version levels suported by wcwidth
is returned by :func:`list_versions`.
Any version string may be specified without error -- the nearest
matching version is selected. When ``latest`` (default), the
highest Unicode version level is used.
:return: The width, in cells, necessary to display the character of
Unicode string character, ``wc``. Returns 0 if the ``wc`` argument has
no printable effect on a terminal (such as NUL '\0'), -1 if ``wc`` is
not printable, or has an indeterminate effect on the terminal, such as
a control character. Otherwise, the number of column positions the
character occupies on a graphic terminal (1 or 2) is returned.
:rtype: int
See :ref:`Specification` for details of cell measurement.
"""
ucs = ord(wc) if wc else 0
# small optimization: early return of 1 for printable ASCII, this provides
# approximately 40% performance improvement for mostly-ascii documents, with
# less than 1% impact to others.
if 32 <= ucs < 0x7f:
return 1
# C0/C1 control characters are -1 for compatibility with POSIX-like calls
if ucs and ucs < 32 or 0x07F <= ucs < 0x0A0:
return -1
_unicode_version = _wcmatch_version(unicode_version)
# Zero width
if _bisearch(ucs, ZERO_WIDTH[_unicode_version]):
return 0
# 1 or 2 width
return 1 + _bisearch(ucs, WIDE_EASTASIAN[_unicode_version])
def wcswidth(pwcs, n=None, unicode_version='auto'):
"""
Given a unicode string, return its printable length on a terminal.
:param str pwcs: Measure width of given unicode string.
:param int n: When ``n`` is None (default), return the length of the entire
string, otherwise only the first ``n`` characters are measured. This
argument exists only for compatibility with the C POSIX function
signature. It is suggested instead to use python's string slicing
capability, ``wcswidth(pwcs[:n])``
:param str unicode_version: An explicit definition of the unicode version
level to use for determination, may be ``auto`` (default), which uses
the Environment Variable, ``UNICODE_VERSION`` if defined, or the latest
available unicode version, otherwise.
:rtype: int
:returns: The width, in cells, needed to display the first ``n`` characters
of the unicode string ``pwcs``. Returns ``-1`` for C0 and C1 control
characters!
See :ref:`Specification` for details of cell measurement.
"""
# this 'n' argument is a holdover for POSIX function
_unicode_version = None
end = len(pwcs) if n is None else n
width = 0
idx = 0
last_measured_char = None
while idx < end:
char = pwcs[idx]
if char == '\u200D':
# Zero Width Joiner, do not measure this or next character
idx += 2
continue
if char == '\uFE0F' and last_measured_char:
# on variation selector 16 (VS16) following another character,
# conditionally add '1' to the measured width if that character is
# known to be converted from narrow to wide by the VS16 character.
if _unicode_version is None:
_unicode_version = _wcversion_value(_wcmatch_version(unicode_version))
if _unicode_version >= (9, 0, 0):
width += _bisearch(ord(last_measured_char), VS16_NARROW_TO_WIDE["9.0.0"])
last_measured_char = None
idx += 1
continue
# measure character at current index
wcw = wcwidth(char, unicode_version)
if wcw < 0:
# early return -1 on C0 and C1 control characters
return wcw
if wcw > 0:
# track last character measured to contain a cell, so that
# subsequent VS-16 modifiers may be understood
last_measured_char = char
width += wcw
idx += 1
return width
@lru_cache(maxsize=128)
def _wcversion_value(ver_string):
"""
Integer-mapped value of given dotted version string.
:param str ver_string: Unicode version string, of form ``n.n.n``.
:rtype: tuple(int)
:returns: tuple of digit tuples, ``tuple(int, [...])``.
"""
retval = tuple(map(int, (ver_string.split('.'))))
return retval
@lru_cache(maxsize=8)
def _wcmatch_version(given_version):
"""
Return nearest matching supported Unicode version level.
If an exact match is not determined, the nearest lowest version level is
returned after a warning is emitted. For example, given supported levels
``4.1.0`` and ``5.0.0``, and a version string of ``4.9.9``, then ``4.1.0``
is selected and returned:
>>> _wcmatch_version('4.9.9')
'4.1.0'
>>> _wcmatch_version('8.0')
'8.0.0'
>>> _wcmatch_version('1')
'4.1.0'
:param str given_version: given version for compare, may be ``auto``
(default), to select Unicode Version from Environment Variable,
``UNICODE_VERSION``. If the environment variable is not set, then the
latest is used.
:rtype: str
:returns: unicode string.
"""
# Design note: the choice to return the same type that is given certainly
# complicates it for python 2 str-type, but allows us to define an api that
# uses 'string-type' for unicode version level definitions, so all of our
# example code works with all versions of python.
#
# That, along with the string-to-numeric and comparisons of earliest,
# latest, matching, or nearest, greatly complicates this function.
# Performance is somewhat curbed by memoization.
unicode_versions = list_versions()
latest_version = unicode_versions[-1]
if given_version == 'auto':
given_version = os.environ.get(
'UNICODE_VERSION',
'latest')
if given_version == 'latest':
# default match, when given as 'latest', use the most latest unicode
# version specification level supported.
return latest_version
if given_version in unicode_versions:
# exact match, downstream has specified an explicit matching version
# matching any value of list_versions().
return given_version
# The user's version is not supported by ours. We return the newest unicode
# version level that we support below their given value.
try:
cmp_given = _wcversion_value(given_version)
except ValueError:
# submitted value raises ValueError in int(), warn and use latest.
warnings.warn("UNICODE_VERSION value, {given_version!r}, is invalid. "
"Value should be in form of `integer[.]+', the latest "
"supported unicode version {latest_version!r} has been "
"inferred.".format(given_version=given_version,
latest_version=latest_version))
return latest_version
# given version is less than any available version, return earliest
# version.
earliest_version = unicode_versions[0]
cmp_earliest_version = _wcversion_value(earliest_version)
if cmp_given <= cmp_earliest_version:
# this probably isn't what you wanted, the oldest wcwidth.c you will
# find in the wild is likely version 5 or 6, which we both support,
# but it's better than not saying anything at all.
warnings.warn("UNICODE_VERSION value, {given_version!r}, is lower "
"than any available unicode version. Returning lowest "
"version level, {earliest_version!r}".format(
given_version=given_version,
earliest_version=earliest_version))
return earliest_version
# create list of versions which are less than our equal to given version,
# and return the tail value, which is the highest level we may support,
# or the latest value we support, when completely unmatched or higher
# than any supported version.
#
# function will never complete, always returns.
for idx, unicode_version in enumerate(unicode_versions):
# look ahead to next value
try:
cmp_next_version = _wcversion_value(unicode_versions[idx + 1])
except IndexError:
# at end of list, return latest version
return latest_version
# Maybe our given version has less parts, as in tuple(8, 0), than the
# next compare version tuple(8, 0, 0). Test for an exact match by
# comparison of only the leading dotted piece(s): (8, 0) == (8, 0).
if cmp_given == cmp_next_version[:len(cmp_given)]:
return unicode_versions[idx + 1]
# Or, if any next value is greater than our given support level
# version, return the current value in index. Even though it must
# be less than the given value, it's our closest possible match. That
# is, 4.1 is returned for given 4.9.9, where 4.1 and 5.0 are available.
if cmp_next_version > cmp_given:
return unicode_version
assert False, ("Code path unreachable", given_version, unicode_versions) # pragma: no cover