Skip to content

Commit 7c77f39

Browse files
committed
Merge pull request #471 from amlitzer/iabbr-contenteditable
Make :iabbr work in contenteditable text boxes
2 parents f20cfdb + e26157f commit 7c77f39

File tree

1 file changed

+26
-7
lines changed

1 file changed

+26
-7
lines changed

common/content/editor.js

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -447,12 +447,21 @@ const Editor = Module("editor", {
447447
let textbox = Editor.getEditor();
448448
if (!textbox)
449449
return false;
450-
let text = textbox.value;
450+
let text = '';
451+
let currStart = 0;
452+
let currEnd = 0;
453+
if (textbox instanceof Window) {
454+
text = textbox.getSelection().getRangeAt(0).startContainer.data;
455+
currStart = textbox.getSelection().getRangeAt(0).startOffset;
456+
currEnd = textbox.getSelection().getRangeAt(0).endOffset;
457+
} else {
458+
text = textbox.value;
459+
currStart = textbox.selectionStart;
460+
currEnd = textbox.selectionEnd;
461+
}
451462
if (typeof text !== "string")
452463
return false;
453464

454-
let currStart = textbox.selectionStart;
455-
let currEnd = textbox.selectionEnd;
456465
let foundWord = text.substring(0, currStart).replace(/.*[\s\n]/gm, '').match(RegExp('(' + abbreviations._match + ')$'));
457466
if (!foundWord)
458467
return true;
@@ -462,10 +471,20 @@ const Editor = Module("editor", {
462471
if (abbrev) {
463472
let len = foundWord.length;
464473
let abbrText = abbrev.text;
465-
text = text.substring(0, currStart - len) + abbrText + text.substring(currStart);
466-
textbox.value = text;
467-
textbox.selectionStart = currStart - len + abbrText.length;
468-
textbox.selectionEnd = currEnd - len + abbrText.length;
474+
if (textbox instanceof Window) {
475+
let r = textbox.getSelection().getRangeAt(0);
476+
r.setStart(r.startContainer, currStart - len);
477+
r.deleteContents();
478+
let textNode = document.createTextNode(abbrText);
479+
r.insertNode(textNode);
480+
r.selectNodeContents(textNode);
481+
textbox.getSelection().collapseToEnd();
482+
} else {
483+
text = text.substring(0, currStart - len) + abbrText + text.substring(currStart);
484+
textbox.value = text;
485+
textbox.selectionStart = currStart - len + abbrText.length;
486+
textbox.selectionEnd = currEnd - len + abbrText.length;
487+
}
469488
}
470489

471490
return true;

0 commit comments

Comments
 (0)