Source code for wcwidth.hyperlink

"""
OSC 8 hyperlink parsing and measurement.

.. versionadded:: 0.7.0
"""

from __future__ import annotations

# std imports
import re

import typing

# local
from ._width import width as _width
from .escape_sequences import _SEQUENCE_CLASSIFY

HYPERLINK_OPEN_RE = re.compile(r'\x1b]8;([^;]*);([^\x07\x1b]*)(\x07|\x1b\\)')
HYPERLINK_CLOSE_RE = re.compile(r'\x1b]8;;(\x07|\x1b\\)')


[docs] class HyperlinkParams(typing.NamedTuple): r""" Parsed parameters from an OSC 8 hyperlink open sequence. :param url: The hyperlink URL. :param params: Colon-separated metadata string (often empty). :param terminator: Sequence terminator (``\x07`` or ``\x1b\\``). """ url: str params: str = '' terminator: str = '\x07' @classmethod def parse(cls, seq: str) -> HyperlinkParams | None: r""" Parse an OSC 8 open sequence string. Returns ``None`` if *seq* is not a valid OSC 8 open. Example:: >>> HyperlinkParams.parse('\x1b]8;;http://example.com\x07') HyperlinkParams(url='http://example.com', params='', terminator='\\x07') """ m = HYPERLINK_OPEN_RE.match(seq) if m is None: return None return cls(url=m.group(2), params=m.group(1), terminator=m.group(3)) def make_open(self) -> str: """Generate the OSC 8 open escape sequence.""" return f'\x1b]8;{self.params};{self.url}{self.terminator}' def make_close(self) -> str: """Generate the OSC 8 close escape sequence.""" return f'\x1b]8;;{self.terminator}'