Skip to content

Instantly share code, notes, and snippets.

@addam
Created November 4, 2018 19:29
Show Gist options
  • Save addam/6f077e20162e64f8355df73121620940 to your computer and use it in GitHub Desktop.
Save addam/6f077e20162e64f8355df73121620940 to your computer and use it in GitHub Desktop.
Code indent function for <textarea onkeydown="tryIndent(event)">
function tryIndent(event) {
if (event.code != "Tab") {
return;
}
event.preventDefault();
var text = event.target;
var start = Math.max(text.value.lastIndexOf("\n", text.selectionStart - 1), 0);
var end = text.selectionEnd;
var str = text.value.slice(start, end);
var origLength = str.length;
if (event.shiftKey) {
str = (str.startsWith(" ") ? str.slice(1) : str).replace(/\n /g, "\n");
} else {
str = (start == 0 ? " " + str : str).replace(/\n/g, "\n ");
}
text.value = text.value.slice(0, start) + str + text.value.slice(end);
text.selectionStart = (start == 0) ? 0 : start + 1;
text.selectionEnd = end + str.length - origLength;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment