A community-maintained Python framework for creating mathematical animations.
Markup text (#855)
Philipp Imhofc560ab397de7
diff --git a/docs/source/changelog.rst b/docs/source/changelog.rstindex 33544dbe3..5f73fb89b 100644--- a/docs/source/changelog.rst+++ b/docs/source/changelog.rst@@ -203,4 +203,4 @@ Other Changes#. Cleanup 3b1b Specific Files#. Rename package from manimlib to manim#. Move all imports to :code:`__init__`, so :code:`from manim import *` replaces :code:`from manimlib.imports import *`-#. Global dir variable handling has been removed. Instead :code:`initialize_directories`, if needed, overrides the values from the cfg files at runtime.\ No newline at end of file+#. Global dir variable handling has been removed. Instead :code:`initialize_directories`, if needed, overrides the values from the cfg files at runtime.diff --git a/manim/mobject/svg/text_mobject.py b/manim/mobject/svg/text_mobject.pyindex febcca661..bf1b1d2ff 100644--- a/manim/mobject/svg/text_mobject.py+++ b/manim/mobject/svg/text_mobject.py@@ -42,7 +42,7 @@ Examples"""-__all__ = ["Text", "Paragraph", "CairoText"]+__all__ = ["Text", "Paragraph", "CairoText", "MarkupText"]import copy@@ -63,6 +63,8 @@ from ...mobject.geometry import Dotfrom ...mobject.svg.svg_mobject import SVGMobjectfrom ...mobject.types.vectorized_mobject import VGroupfrom ...utils.color import WHITE+from ...utils.color import Colors+TEXT_MOB_SCALE_FACTOR = 0.05@@ -101,6 +103,58 @@ def remove_invisible_chars(mobject):return mobject_without_dots+class PangoUtils:+ @staticmethod+ def str2style(string: str) -> pangocffi.Style:+ """Internally used function. Converts text to Pango Understandable Styles."""+ if string == NORMAL:+ return pangocffi.Style.NORMAL+ elif string == ITALIC:+ return pangocffi.Style.ITALIC+ elif string == OBLIQUE:+ return pangocffi.Style.OBLIQUE+ else:+ raise AttributeError("There is no Style Called %s" % string)++ @staticmethod+ def str2weight(string: str) -> pangocffi.Weight:+ """Internally used function. Convert text to Pango Understandable Weight"""+ if string == NORMAL:+ return pangocffi.Weight.NORMAL+ elif string == BOLD:+ return pangocffi.Weight.BOLD+ elif string == THIN:+ return pangocffi.Weight.THIN+ elif string == ULTRALIGHT:+ return pangocffi.Weight.ULTRALIGHT+ elif string == LIGHT:+ return pangocffi.Weight.LIGHT+ elif string == SEMILIGHT:+ return pangocffi.Weight.SEMILIGHT+ elif string == BOOK:+ return pangocffi.Weight.BOOK+ elif string == MEDIUM:+ return pangocffi.Weight.MEDIUM+ elif string == SEMIBOLD:+ return pangocffi.Weight.SEMIBOLD+ elif string == ULTRABOLD:+ return pangocffi.Weight.ULTRABOLD+ elif string == HEAVY:+ return pangocffi.Weight.HEAVY+ elif string == ULTRAHEAVY:+ return pangocffi.Weight.ULTRAHEAVY+ else:+ raise AttributeError("There is no Font Weight Called %s" % string)++ @staticmethod+ def remove_last_M(file_name: str) -> None:+ with open(file_name, "r") as fpr:+ content = fpr.read()+ content = re.sub(r'Z M [^A-Za-z]*? "\/>', 'Z "/>', content)+ with open(file_name, "w") as fpw:+ fpw.write(content)++class TextSetting(object):def __init__(self, start, end, font, slant, weight, line_num=-1):self.start = start@@ -118,13 +172,6 @@ class CairoText(SVGMobject):in the given text. In particular, slicing is possible.-- .. WARNING::-- Using a :class:`.Transform` on text with leading whitespace can look- `weird <https://github.com/3b1b/manim/issues/1067>`_. Consider using- :meth:`remove_invisible_chars` to resolve this issue.-Tests-----@@ -151,8 +198,8 @@ class CairoText(SVGMobject):gradient=None,line_spacing=-1,size=1,- slant=NORMAL,- weight=NORMAL,+ slant: str = NORMAL,+ weight: str = NORMAL,t2c=None,t2f=None,t2g=None,@@ -200,7 +247,7 @@ class CairoText(SVGMobject):else:self.line_spacing = self.size + self.size * self.line_spacingfile_name = self.text2svg()- self.remove_last_M(file_name)+ PangoUtils.remove_last_M(file_name)SVGMobject.__init__(self,file_name,@@ -256,7 +303,7 @@ class CairoText(SVGMobject):or self.text[char_index] == "\t"or self.text[char_index] == "\n"):- space = Dot(redius=0, fill_opacity=0, stroke_opacity=0)+ space = Dot(radius=0, fill_opacity=0, stroke_opacity=0)if char_index == 0:space.move_to(self.submobjects[submobjects_char_index].get_center())else:@@ -269,13 +316,6 @@ class CairoText(SVGMobject):submobjects_char_index += 1return chars- def remove_last_M(self, file_name):- with open(file_name, "r") as fpr:- content = fpr.read()- content = re.sub(r'Z M [^A-Za-z]*? "\/>', 'Z "/>', content)- with open(file_name, "w") as fpw:- fpw.write(content)-def find_indexes(self, word, text):m = re.match(r"\[([0-9\-]{0,}):([0-9\-]{0,})\]", word)if m:@@ -433,11 +473,6 @@ class Paragraph(VGroup)::class:`.VGroup` containing all the lines. In this context, every line isconstructed as a :class:`.VGroup` of characters contained in the line.- .. WARNING::-- Using a :class:`.Transform` on text with leading whitespace can look- `weird <https://github.com/3b1b/manim/issues/1067>`_. Consider using- :meth:`remove_invisible_chars` to resolve this issue.Parameters----------@@ -714,12 +749,6 @@ class Text(SVGMobject):>>> Text('The horse does not eat cucumber salad.')Text('The horse does not eat cucumber salad.')- .. WARNING::-- Using a :class:`.Transform` on text with leading whitespace can look- `weird <https://github.com/3b1b/manim/issues/1067>`_. Consider using- :meth:`remove_invisible_chars` to resolve this issue.-"""def __init__(@@ -731,8 +760,8 @@ class Text(SVGMobject):size: int = 1,line_spacing: int = -1,font: str = "",- slant=NORMAL,- weight=NORMAL,+ slant: str = NORMAL,+ weight: str = NORMAL,t2c: Dict[str, str] = None,t2f: Dict[str, str] = None,t2g: Dict[str, tuple] = None,@@ -793,7 +822,7 @@ class Text(SVGMobject):else:self.line_spacing = self.size + self.size * self.line_spacingfile_name = self.text2svg()- self.remove_last_M(file_name)+ PangoUtils.remove_last_M(file_name)SVGMobject.__init__(self,file_name,@@ -810,7 +839,6 @@ class Text(SVGMobject):if self.disable_ligatures:self.submobjects = [*self.gen_chars()]self.chars = VGroup(*self.submobjects)- self.chars = VGroup(*self.submobjects)self.text = text_without_tabs.replace(" ", "").replace("\n", "")nppc = self.n_points_per_cubic_curvefor each in self:@@ -847,7 +875,7 @@ class Text(SVGMobject):submobjects_char_index = 0for char_index in range(self.text.__len__()):if self.text[char_index] in (" ", "\t", "\n"):- space = Dot(redius=0, fill_opacity=0, stroke_opacity=0)+ space = Dot(radius=0, fill_opacity=0, stroke_opacity=0)if char_index == 0:space.move_to(self.submobjects[submobjects_char_index].get_center())else:@@ -860,14 +888,6 @@ class Text(SVGMobject):submobjects_char_index += 1return chars- def remove_last_M(self, file_name: str): # pylint: disable=invalid-name- """Internally used. Use to format the rendered SVG files."""- with open(file_name, "r") as fpr:- content = fpr.read()- content = re.sub(r'Z M [^A-Za-z]*? "\/>', 'Z "/>', content)- with open(file_name, "w") as fpw:- fpw.write(content)-def find_indexes(self, word: str, text: str):"""Internally used function. Finds the indexes of ``text`` in ``word``."""temp = re.match(r"\[([0-9\-]{0,}):([0-9\-]{0,})\]", word)@@ -918,46 +938,6 @@ class Text(SVGMobject):for start, end in self.find_indexes(word, self.original_text):self.chars[start:end].set_color_by_gradient(*gradient)- def str2style(self, string):- """Internally used function. Converts text to Pango Understandable Styles."""- if string == NORMAL:- return pangocffi.Style.NORMAL- elif string == ITALIC:- return pangocffi.Style.ITALIC- elif string == OBLIQUE:- return pangocffi.Style.OBLIQUE- else:- raise AttributeError("There is no Style Called %s" % string)-- def str2weight(self, string):- """Internally used function. Convert text to Pango Understandable Weight"""- if string == NORMAL:- return pangocffi.Weight.NORMAL- elif string == BOLD:- return pangocffi.Weight.BOLD- elif string == THIN:- return pangocffi.Weight.THIN- elif string == ULTRALIGHT:- return pangocffi.Weight.ULTRALIGHT- elif string == LIGHT:- return pangocffi.Weight.LIGHT- elif string == SEMILIGHT:- return pangocffi.Weight.SEMILIGHT- elif string == BOOK:- return pangocffi.Weight.BOOK- elif string == MEDIUM:- return pangocffi.Weight.MEDIUM- elif string == SEMIBOLD:- return pangocffi.Weight.SEMIBOLD- elif string == ULTRABOLD:- return pangocffi.Weight.ULTRABOLD- elif string == HEAVY:- return pangocffi.Weight.HEAVY- elif string == ULTRAHEAVY:- return pangocffi.Weight.ULTRAHEAVY- else:- raise AttributeError("There is no Font Weight Called %s" % string)-def text2hash(self):"""Internally used function.Generates ``sha256`` hash for file name.@@ -967,6 +947,7 @@ class Text(SVGMobject):) # to differentiate Text and CairoTextsettings += str(self.t2f) + str(self.t2s) + str(self.t2w)settings += str(self.line_spacing) + str(self.size)+ settings += str(self.disable_ligatures)id_str = self.text + settingshasher = hashlib.sha256()hasher.update(id_str.encode())@@ -1041,8 +1022,8 @@ class Text(SVGMobject):layout.set_width(pangocffi.units_from_double(600))for setting in settings:family = setting.font- style = self.str2style(setting.slant)- weight = self.str2weight(setting.weight)+ style = PangoUtils.str2style(setting.slant)+ weight = PangoUtils.str2weight(setting.weight)text = self.text[setting.start : setting.end].replace("\n", " ")fontdesc = pangocffi.FontDescription()fontdesc.set_size(pangocffi.units_from_double(size))@@ -1060,7 +1041,9 @@ class Text(SVGMobject):pangocairocffi.update_layout(context, layout)if disable_liga:text = escape(text)- layout.set_markup(f"<span font_features='liga=0'>{text}</span>")+ layout.set_markup(+ f"<span font_features='liga=0,dlig=0,clig=0,hlig=0'>{text}</span>"+ )else:layout.set_text(text)logger.debug(f"Setting Text {text}")@@ -1068,3 +1051,430 @@ class Text(SVGMobject):offset_x += pangocffi.units_to_double(layout.get_size()[0])surface.finish()return file_name+++class MarkupText(SVGMobject):+ r"""Display (non-LaTeX) text rendered using `Pango <https://pango.gnome.org/>`_.++ Text objects behave like a :class:`.VGroup`-like iterable of all characters+ in the given text. In particular, slicing is possible. Text can be formatted+ using different tags:++ - ``<b>bold</b>``, ``<i>italic</i>`` and ``<b><i>bold+italic</i></b>``+ - ``<ul>underline</ul>`` and ``<s>strike through</s>``+ - ``<tt>typewriter font</tt>``+ - ``<big>bigger font</big>`` and ``<small>smaller font</small>``+ - ``<sup>superscript</sup>`` and ``<sub>subscript</sub>``+ - ``<span underline="double">double underline</span>``+ - ``<span underline="error">error underline</span>``+ - ``<span font_family="sans">temporary change of font</span>``+ - ``<color col="RED">temporary change of color</color>``; colors can be specified as Manim constants like ``RED`` or ``YELLOW`` or as hex triples like ``#aabbaa``+ - ``<gradient from="YELLOW" to="RED">temporary gradient</gradient>``; colors specified as above++ If your text contains ligatures, the :class:`MarkupText` class may incorrectly determine+ the first and last letter to be colored. This is due to the fact that e.g. ``fl``+ are two characters, but might be set as one single glyph, a ligature. If your language does+ not depend on ligatures, consider setting ``disable_ligatures=True``. If you cannot+ or do not want to do without ligatures, the ``gradient`` and ``color`` tag support+ an optional attribute ``offset`` which can be used to compensate for that error.+ Usage is as follows:++ - ``<color col="RED" offset="1">red text</color>`` to *start* coloring one letter earlier+ - ``<color col="RED" offset=",1">red text</color>`` to *end* coloring one letter earlier+ - ``<color col="RED" offset="2,1">red text</color>`` to *start* coloring two letters earlier and *end* one letter earlier++ Specifying a second offset may be necessary if the text to be colored does+ itself contain ligatures. The same can happen when using HTML entities for+ special chars.++ Escaping of special characters: ``>`` *should* be written as ``>`` whereas ``<`` and+ ``&`` *must* be written as ``<`` and ``&``.++ You can find more information about Pango markup formatting at the+ corresponding documentation page:+ `Pango Markup <https://developer.gnome.org/pango/stable/pango-Markup.html>`_.+ Please be aware that not all features are supported by this class and that+ the ``<color>`` and ``<gradient>`` tags mentioned above are not supported by Pango.++ Parameters+ ----------+ text : :class:`str`+ The text that need to created as mobject.+ fill_opacity : :class:`int`+ The fill opacity with 1 meaning opaque and 0 meaning transparent.+ stroke_width : :class:`int`+ Stroke width.+ color : :class:`str`+ Global color setting for the entire text. Local overrides are possible.+ size : :class:`int`+ Font size.+ line_spacing : :class:`int`+ Line spacing.+ font : :class:`str`+ Global font setting for the entire text. Local overrides are possible.+ slant : :class:`str`+ Global slant setting, e.g. `NORMAL` or `ITALIC`. Local overrides are possible.+ weight : :class:`str`+ Global weight setting, e.g. `NORMAL` or `BOLD`. Local overrides are possible.+ gradient: :class:`tuple`+ Global gradient setting. Local overrides are possible.+++ Returns+ -------+ :class:`MarkupText`+ The text displayed in form of a :class:`.VGroup`-like mobject.++ Examples+ ---------++ .. manim:: BasicMarkupExample+ :save_last_frame:++ class BasicMarkupExample(Scene):+ def construct(self):+ text1 = MarkupText("<b>foo</b> <i>bar</i> <b><i>foobar</i></b>")+ text2 = MarkupText("<s>foo</s> <u>bar</u> <big>big</big> <small>small</small>")+ text3 = MarkupText("H<sub>2</sub>O and H<sub>3</sub>O<sup>+</sup>")+ text4 = MarkupText("type <tt>help</tt> for help")+ text5 = MarkupText(+ '<span underline="double">foo</span> <span underline="error">bar</span>'+ )+ group = VGroup(text1, text2, text3, text4, text5).arrange(DOWN)+ self.add(group)++ .. manim:: ColorExample+ :save_last_frame:++ class ColorExample(Scene):+ def construct(self):+ text1 = MarkupText(+ 'all in red <color col="YELLOW">except this</color>', color=RED+ )+ text2 = MarkupText("nice gradient", gradient=(BLUE, GREEN))+ text3 = MarkupText(+ 'nice <gradient from="RED" to="YELLOW">intermediate</gradient> gradient',+ gradient=(BLUE, GREEN),+ )+ text4 = MarkupText(+ 'fl ligature <color col="#00ff00">causing trouble</color> here'+ )+ text5 = MarkupText(+ 'fl ligature <color col="#00ff00" offset="1">defeated</color> with offset'+ )+ text6 = MarkupText(+ 'fl ligature <color col="GREEN" offset="1">floating</color> inside'+ )+ text7 = MarkupText(+ 'fl ligature <color col="GREEN" offset="1,1">floating</color> inside'+ )+ group = VGroup(text1, text2, text3, text4, text5, text6, text7).arrange(DOWN)+ self.add(group)++ .. manim:: FontExample+ :save_last_frame:++ class FontExample(Scene):+ def construct(self):+ text1 = MarkupText(+ 'all in sans <span font_family="serif">except this</span>', font="sans"+ )+ text2 = MarkupText(+ '<span font_family="serif">mixing</span> <span font_family="sans">fonts</span> <span font_family="monospace">is ugly</span>'+ )+ text3 = MarkupText("special char > or >")+ text4 = MarkupText("special char < and &")+ group = VGroup(text1, text2, text3, text4).arrange(DOWN)+ self.add(group)++ .. manim:: NewlineExample+ :save_last_frame:++ class NewlineExample(Scene):+ def construct(self):+ text = MarkupText('foooo<color col="RED">oo\nbaa</color>aar')+ self.add(text)++ .. manim:: NoLigaturesExample+ :save_last_frame:++ class NoLigaturesExample(Scene):+ def construct(self):+ text1 = MarkupText('fl<color col="RED">oat</color>ing')+ text2 = MarkupText('fl<color col="RED">oat</color>ing', disable_ligatures=True)+ group = VGroup(text1, text2).arrange(DOWN)+ self.add(group)+++ As :class:`MarkupText` uses Pango to render text, rendering non-English+ characters is easily possible:++ .. manim:: MultiLanguage+ :save_last_frame:++ class MultiLanguage(Scene):+ def construct(self):+ morning = MarkupText("வணக்கம்", font="sans-serif")+ chin = MarkupText(+ '見 角 言 谷 辛 <color col="BLUE">辰 辵 邑</color> 酉 釆 里!'+ ) # works as in ``Text``.+ mess = MarkupText("Multi-Language", style=BOLD)+ russ = MarkupText("Здравствуйте मस नम म ", font="sans-serif")+ hin = MarkupText("नमस्ते", font="sans-serif")+ japanese = MarkupText("臂猿「黛比」帶著孩子", font="sans-serif")+ group = VGroup(morning, chin, mess, russ, hin, japanese).arrange(DOWN)+ self.add(group)+++ Tests+ -----++ Check that the creation of :class:`~.MarkupText` works::++ >>> MarkupText('The horse does not eat cucumber salad.')+ MarkupText('The horse does not eat cucumber salad.')++ """++ def __init__(+ self,+ text: str,+ fill_opacity: int = 1,+ stroke_width: int = 0,+ color: str = WHITE,+ size: int = 1,+ line_spacing: int = -1,+ font: str = "",+ slant: str = NORMAL,+ weight: str = NORMAL,+ gradient: tuple = None,+ tab_width: int = 4,+ height: int = None,+ width: int = None,+ should_center: bool = True,+ unpack_groups: bool = True,+ disable_ligatures: bool = False,+ **kwargs,+ ):+ self.text = text+ self.size = size+ self.line_spacing = line_spacing+ self.font = font+ self.slant = slant+ self.weight = weight+ self.gradient = gradient+ self.tab_width = tab_width++ self.original_text = text+ self.disable_ligatures = disable_ligatures+ text_without_tabs = text+ if "\t" in text:+ text_without_tabs = text.replace("\t", " " * self.tab_width)++ colormap = self.extract_color_tags()+ gradientmap = self.extract_gradient_tags()++ if self.line_spacing == -1:+ self.line_spacing = self.size + self.size * 0.3+ else:+ self.line_spacing = self.size + self.size * self.line_spacing++ file_name = self.text2svg()+ PangoUtils.remove_last_M(file_name)+ SVGMobject.__init__(+ self,+ file_name,+ color=color,+ fill_opacity=fill_opacity,+ stroke_width=stroke_width,+ height=height,+ width=width,+ should_center=should_center,+ unpack_groups=unpack_groups,+ **kwargs,+ )+ self.chars = VGroup(*self.submobjects)+ self.text = text_without_tabs.replace(" ", "").replace("\n", "")++ nppc = self.n_points_per_cubic_curve+ for each in self:+ if len(each.points) == 0:+ continue+ points = each.points+ last = points[0]+ each.clear_points()+ for index, point in enumerate(points):+ each.append_points([point])+ if (+ index != len(points) - 1+ and (index + 1) % nppc == 0+ and any(point != points[index + 1])+ ):+ each.add_line_to(last)+ last = points[index + 1]+ each.add_line_to(last)++ if self.gradient:+ self.set_color_by_gradient(*self.gradient)+ for col in colormap:+ self.chars[+ col["start"]+ - col["start_offset"] : col["end"]+ - col["start_offset"]+ - col["end_offset"]+ ].set_color(self._parse_color(col["color"]))+ for grad in gradientmap:+ self.chars[+ grad["start"]+ - grad["start_offset"] : grad["end"]+ - grad["start_offset"]+ - grad["end_offset"]+ ].set_color_by_gradient(+ *(self._parse_color(grad["from"]), self._parse_color(grad["to"]))+ )+ # anti-aliasing+ if self.height is None and self.width is None:+ self.scale(TEXT_MOB_SCALE_FACTOR)++ def text2hash(self):+ """Generates ``sha256`` hash for file name."""+ settings = (+ "MARKUPPANGO" + self.font + self.slant + self.weight+ ) # to differentiate from classical Pango Text+ settings += str(self.line_spacing) + str(self.size)+ settings += str(self.disable_ligatures)+ id_str = self.text + settings+ hasher = hashlib.sha256()+ hasher.update(id_str.encode())+ return hasher.hexdigest()[:16]++ def text2svg(self):+ """Convert the text to SVG using Pango."""+ size = self.size * 10+ line_spacing = self.line_spacing * 10+ dir_name = config.get_dir("text_dir")+ disable_liga = self.disable_ligatures+ if not os.path.exists(dir_name):+ os.makedirs(dir_name)+ hash_name = self.text2hash()+ file_name = os.path.join(dir_name, hash_name) + ".svg"+ if os.path.exists(file_name):+ return file_name+ surface = cairocffi.SVGSurface(file_name, 600, 400)+ context = cairocffi.Context(surface)+ context.move_to(START_X, START_Y)+ layout = pangocairocffi.create_layout(context)+ layout.set_width(pangocffi.units_from_double(600))++ fontdesc = pangocffi.FontDescription()+ fontdesc.set_size(pangocffi.units_from_double(size))+ if self.font:+ fontdesc.set_family(self.font)+ fontdesc.set_style(PangoUtils.str2style(self.slant))+ fontdesc.set_weight(PangoUtils.str2weight(self.weight))+ layout.set_font_description(fontdesc)++ context.move_to(START_X, START_Y)+ pangocairocffi.update_layout(context, layout)+ if disable_liga:+ layout.set_markup(+ f"<span font_features='liga=0,dlig=0,clig=0,hlig=0'>{self.text}</span>"+ )+ else:+ layout.set_markup(self.text)+ logger.debug(f"Setting Text {self.text}")+ pangocairocffi.show_layout(context, layout)+ surface.finish()+ return file_name++ def _count_real_chars(self, s):+ """Counts characters that will be displayed.++ This is needed for partial coloring or gradients, because space+ counts to the text's `len`, but has no corresponding character."""+ count = 0+ level = 0+ # temporarily replace HTML entities by single char+ s = re.sub("&[^;]+;", "x", s)+ for c in s:+ if c == "<":+ level += 1+ if c == ">" and level > 0:+ level -= 1+ elif c != " " and c != "\t" and level == 0:+ count += 1+ return count++ def extract_gradient_tags(self):+ """Used to determine which parts (if any) of the string should be formatted+ with a gradient.++ Removes the ``<gradient>`` tag, as it is not part of Pango's markup and would cause an error.+ """+ tags = re.finditer(+ '<gradient\s+from="([^"]+)"\s+to="([^"]+)"(\s+offset="([^"]+)")?>(.+?)</gradient>',+ self.original_text,+ re.S,+ )+ gradientmap = []+ for tag in tags:+ start = self._count_real_chars(self.original_text[: tag.start(0)])+ end = start + self._count_real_chars(tag.group(5))+ offsets = tag.group(4).split(",") if tag.group(4) else [0]+ start_offset = int(offsets[0]) if offsets[0] else 0+ end_offset = int(offsets[1]) if len(offsets) == 2 and offsets[1] else 0++ gradientmap.append(+ {+ "start": start,+ "end": end,+ "from": tag.group(1),+ "to": tag.group(2),+ "start_offset": start_offset,+ "end_offset": end_offset,+ }+ )+ self.text = re.sub("<gradient[^>]+>(.+?)</gradient>", r"\1", self.text, 0, re.S)+ return gradientmap++ def _parse_color(self, col):+ """Parse color given in ``<color>`` or ``<gradient>`` tags."""+ if re.match("#[0-9a-f]{6}", col):+ return col+ else:+ return Colors[col.lower()].value++ def extract_color_tags(self):+ """Used to determine which parts (if any) of the string should be formatted+ with a custom color.++ Removes the ``<color>`` tag, as it is not part of Pango's markup and would cause an error.+ """+ tags = re.finditer(+ '<color\s+col="([^"]+)"(\s+offset="([^"]+)")?>(.+?)</color>',+ self.original_text,+ re.S,+ )++ colormap = []+ for tag in tags:+ start = self._count_real_chars(self.original_text[: tag.start(0)])+ end = start + self._count_real_chars(tag.group(4))+ offsets = tag.group(3).split(",") if tag.group(3) else [0]+ start_offset = int(offsets[0]) if offsets[0] else 0+ end_offset = int(offsets[1]) if len(offsets) == 2 and offsets[1] else 0++ colormap.append(+ {+ "start": start,+ "end": end,+ "color": tag.group(1),+ "start_offset": start_offset,+ "end_offset": end_offset,+ }+ )+ self.text = re.sub("<color[^>]+>(.+?)</color>", r"\1", self.text, 0, re.S)+ return colormap++ def __repr__(self):+ return f"MarkupText({repr(self.original_text)})"