Commit 1b88d4a0 authored by Robin Sonnabend's avatar Robin Sonnabend

Handle tabs in textareas

/close #67
parent e6eec99e
......@@ -28,6 +28,64 @@ function resize_textarea_delayed(textarea) {
return _inner_resize_textarea_delayed;
}
function tab_on_key_down(textarea) {
function _inner_tab_on_key_down(e) {
console.log(e);
if (e.keyCode == 9) {
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var text = textarea.value;
if (start == end) {
var text_before = text.substring(0, start);
var text_after = text.substring(end);
textarea.value = text_before + "\t" + text_after;
textarea.selectionStart = start+1;
textarea.selectionEnd = end+1;
} else {
var text_before = text.substring(0, start);
var text_center = text.substring(start, end);
var text_after = text.substring(end);
lines = text_center.split("\n");
var forward = !e.shiftKey;
var new_center = "";
if (forward) {
for (var i = 0; i < lines.length; i++) {
new_center += "\t" + lines[i];
if (i != lines.length - 1) {
new_center += "\n";
}
}
textarea.value = text_before + new_center + text_after;
textarea.selectionStart = start;
textarea.selectionEnd = end + lines.length;
} else {
var reduction = 0;
var start_reduction = 0;
for (var i = 0; i < lines.length; i++) {
var newline = lines[i];
if (newline[0] == "\t") {
newline = newline.substring(1);
reduction += 1;
if (i == 0) {
start_reduction += 1;
}
}
new_center += newline;
if (i != lines.length - 1) {
new_center += "\n";
}
}
textarea.value = text_before + new_center + text_after;
textarea.selectionStart = start - start_reduction;
textarea.selectionEnd = end - reduction;
}
}
e.preventDefault();
}
}
return _inner_tab_on_key_down;
}
window.onload=function() {
// toggle expansion
var buttons = document.getElementsByClassName("expansion-button");
......@@ -35,15 +93,17 @@ window.onload=function() {
var button = buttons[i];
button.onclick = toggle_expansion;
}
// resize textarea
// resize of and tabs in textarea
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < textareas.length; i++) {
var textarea = textareas[i];
var delayed = resize_textarea_delayed(textarea);
var tab_func = tab_on_key_down(textarea);
textarea.addEventListener("change", resize_textarea(textarea), false);
textarea.addEventListener("cut", resize_textarea_delayed(textarea), false);
textarea.addEventListener("paste", resize_textarea_delayed(textarea), false);
textarea.addEventListener("drop", resize_textarea_delayed(textarea), false);
textarea.addEventListener("keydown", resize_textarea_delayed(textarea), false);
textarea.addEventListener("cut", delayed, false);
textarea.addEventListener("paste", delayed, false);
textarea.addEventListener("drop", delayed, false);
textarea.addEventListener("keydown", function(e){tab_func(e); delayed()}, false);
resize_textarea(textarea)();
}
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment