Skip to content

Commit 3648538

Browse files
committed
Update codeit.js
1 parent fe40b56 commit 3648538

File tree

1 file changed

+47
-32
lines changed

1 file changed

+47
-32
lines changed

lib/codeit.js

Lines changed: 47 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -586,48 +586,63 @@ class CodeitElement extends HTMLElement {
586586
// get current selection
587587
const s = window.getSelection();
588588

589-
// if there's no selection
590-
if (s.isCollapsed) {
589+
let selContents = s.toString();
590+
591+
// if selection exists
592+
if (!s.isCollapsed) {
591593

592-
// delete a tab from selection
593-
594+
let lines = selContents.split('\n');
595+
596+
// run on all lines
597+
lines.forEach((line, index) => {
598+
599+
// if line contains a tab
600+
if (line.startsWith(cd.options.tab)) {
601+
602+
// remove tab from line
603+
lines[index] = line.slice(cd.options.tab.length);
604+
605+
}
606+
607+
});
608+
609+
// join lines
610+
selContents = lines.join('\n');
611+
612+
613+
// delete selection
614+
cd.deleteCurrentSelection();
615+
616+
// insert tabbed selection
617+
cd.insert(selContents, { moveToEnd: false });
618+
594619
// get caret pos in text
595620
const pos = cd.getSelection();
596-
597-
let startPos = Math.min(pos.start, pos.end);
598-
let endPos = Math.max(pos.start, pos.end);
599-
600-
// get text before cursor
621+
622+
// restore pos in text
623+
cd.setSelection(pos.start, (pos.start + selContents.length));
601624

602-
cd.setSelection(endPos);
625+
} else {
603626

604-
const before = cd.beforeCursor();
605-
606-
// get padding of line
607-
let [linePadding, lineStartPos] = getPadding(before);
627+
let lastLine = cd.beforeCursor().split('\n');
628+
lastLine = lastLine[lastLine.length-1];
608629

609-
// if line has tabs
610-
if (linePadding.length > 0) {
611-
612-
// delete a tab
630+
// if current line contains a tab
631+
if (lastLine.startsWith(cd.options.tab)) {
613632

614-
const tabLength = cd.options.tab.length;
615-
616-
cd.setSelection(lineStartPos, lineStartPos + tabLength);
617-
633+
// remove tab from line
634+
635+
// get caret pos in text
636+
const pos = cd.getSelection();
637+
638+
// select the tab
639+
cd.setSelection((pos.start - lastLine.length), (pos.start - lastLine.length + cd.options.tab.length));
640+
641+
// delete selection
618642
cd.deleteCurrentSelection();
619643

620644
// restore pos in text
621-
cd.setSelection(lineStartPos + linePadding.length - tabLength, endPos - tabLength);
622-
623-
const selectedTab = window.getSelection().toString().startsWith(cd.options.tab);
624-
625-
if (selectedTab) {
626-
627-
// restore pos in text
628-
cd.setSelection(lineStartPos + linePadding.length, endPos - tabLength);
629-
630-
}
645+
cd.setSelection(pos.start);
631646

632647
}
633648

0 commit comments

Comments
 (0)