diff --git a/src/calibre/gui2/tweak_book/editor/smarts/html.py b/src/calibre/gui2/tweak_book/editor/smarts/html.py
index 6d03a04355..aee0d952f3 100644
--- a/src/calibre/gui2/tweak_book/editor/smarts/html.py
+++ b/src/calibre/gui2/tweak_book/editor/smarts/html.py
@@ -488,15 +488,17 @@ class Smarts(NullSmarts):
editor.setTextCursor(c)
def insert_tag(self, editor, name):
+ m = re.match(r'[a-zA-Z0-9:-]+', name)
+ cname = name if m is None else m.group()
+ self.surround_with_custom_tag(editor, f'<{name}>', f'{cname}>')
+
+ def surround_with_custom_tag(self, editor, opent, close):
editor.highlighter.join()
- name = name.lstrip()
text = self.get_smart_selection(editor, update=True)
c = editor.textCursor()
pos = min(c.position(), c.anchor())
- m = re.match(r'[a-zA-Z0-9:-]+', name)
- cname = name if m is None else m.group()
- c.insertText(f'<{name}>{text}{cname}>')
- c.setPosition(pos + 2 + len(name))
+ c.insertText(f'{opent}{text}{close}')
+ c.setPosition(pos + len(opent))
editor.setTextCursor(c)
def verify_for_spellcheck(self, cursor, highlighter):
diff --git a/src/calibre/gui2/tweak_book/editor/text.py b/src/calibre/gui2/tweak_book/editor/text.py
index 974e977e3b..a8c0541bfa 100644
--- a/src/calibre/gui2/tweak_book/editor/text.py
+++ b/src/calibre/gui2/tweak_book/editor/text.py
@@ -871,19 +871,8 @@ class TextEdit(PlainTextEdit):
'color': ('' % color, ''),
'background-color': ('' % color, ''),
}[formatting]
- left, right = self.get_range_inside_tag()
- c = self.textCursor()
- c.setPosition(left)
- c.setPosition(right, QTextCursor.MoveMode.KeepAnchor)
- prev_text = str(c.selectedText()).rstrip('\0')
- c.insertText(prefix + prev_text + suffix)
- if prev_text:
- right = c.position()
- c.setPosition(left)
- c.setPosition(right, QTextCursor.MoveMode.KeepAnchor)
- else:
- c.setPosition(c.position() - len(suffix))
- self.setTextCursor(c)
+ if hasattr(self.smarts, 'surround_with_custom_tag'):
+ self.smarts.surround_with_custom_tag(self, prefix, suffix)
def insert_image(self, href, fullpage=False, preserve_aspect_ratio=False, width=-1, height=-1):
if width <= 0: