@@ -107,44 +107,44 @@ def parse(self, text: str, strict: bool = False):
107107 @staticmethod
108108 def unparse (text : str , entities : list ):
109109 text = utils .add_surrogates (text )
110- copy = text
110+
111+ entities_offsets = []
111112
112113 for entity in entities :
114+ entity_type = entity .type
113115 start = entity .offset
114116 end = start + entity .length
115117
116- type = entity .type
117-
118- url = entity .url
119- user = entity .user
120-
121- sub = copy [start :end ]
122-
123- if type == "bold" :
124- style = BOLD_DELIM
125- elif type == "italic" :
126- style = ITALIC_DELIM
127- elif type == "underline" :
128- style = UNDERLINE_DELIM
129- elif type == "strike" :
130- style = STRIKE_DELIM
131- elif type == "code" :
132- style = CODE_DELIM
133- elif type == "pre" :
134- style = PRE_DELIM
135- # TODO: Blockquote for MD
136- # elif type == "blockquote":
137- # style = ...
138- elif type == "text_link" :
139- text = text [:start ] + text [start :].replace (sub , '[{1}]({0})' .format (url , sub ), 1 )
140- continue
141- elif type == "text_mention" :
142- text = text [:start ] + text [start :].replace (
143- sub , '[{1}](tg://user?id={0})' .format (user .id , sub ), 1 )
144- continue
118+ if entity_type == "bold" :
119+ start_tag = end_tag = BOLD_DELIM
120+ elif entity_type == "italic" :
121+ start_tag = end_tag = ITALIC_DELIM
122+ elif entity_type == "underline" :
123+ start_tag = end_tag = UNDERLINE_DELIM
124+ elif entity_type == "strike" :
125+ start_tag = end_tag = STRIKE_DELIM
126+ elif entity_type == "code" :
127+ start_tag = end_tag = CODE_DELIM
128+ elif entity_type in ("pre" , "blockquote" ):
129+ start_tag = end_tag = PRE_DELIM
130+ elif entity_type == "text_link" :
131+ url = entity .url
132+ start_tag = "["
133+ end_tag = "]({})" .format (url )
134+ elif entity_type == "text_mention" :
135+ user = entity .user
136+ start_tag = "["
137+ end_tag = "](tg://user?id={})" .format (user .id )
145138 else :
146139 continue
147140
148- text = text [:start ] + text [start :].replace (sub , "{0}{1}{0}" .format (style , sub ), 1 )
141+ entities_offsets .append ((start_tag , start ,))
142+ entities_offsets .append ((end_tag , end ,))
143+
144+ # sorting by offset (desc)
145+ entities_offsets .sort (key = lambda x : - x [1 ])
146+
147+ for entity , offset in entities_offsets :
148+ text = text [:offset ] + entity + text [offset :]
149149
150150 return utils .remove_surrogates (text )
0 commit comments