Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add customizable indentation and unindent #24

Merged
merged 1 commit into from
Dec 19, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 28 additions & 10 deletions src/codeflask.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
function CodeFlask() {

function CodeFlask(indent) {
this.indent = indent || " ";
}

CodeFlask.prototype.run = function(selector, opts) {
Expand Down Expand Up @@ -93,7 +93,9 @@ CodeFlask.prototype.handleInput = function(textarea, highlightCode, highlightPre
input,
selStartPos,
inputVal,
roundedScroll;
roundedScroll,
currentLineStart,
indentLength;

textarea.addEventListener('input', function(e) {
input = this;
Expand All @@ -107,13 +109,29 @@ CodeFlask.prototype.handleInput = function(textarea, highlightCode, highlightPre
input = this,
selStartPos = input.selectionStart,
inputVal = input.value;

// If TAB pressed, insert four spaces
if(e.keyCode === 9){
input.value = inputVal.substring(0, selStartPos) + " " + inputVal.substring(selStartPos, input.value.length);
input.selectionStart = selStartPos + 4;
input.selectionEnd = selStartPos + 4;
e.preventDefault();
currentLineStart = selStartPos - input.value.substr(0, selStartPos).split("\n").pop().length;

// If tab pressed, indent
if (e.keyCode === 9) {
e.preventDefault();

// Allow shift-tab
if (e.shiftKey) {
indentLength = self.indent.length;

// If the current line begins with the indent, unindent
if (inputVal.substring(currentLineStart, currentLineStart + indentLength) == self.indent) {
input.value = inputVal.substring(0, currentLineStart) +
inputVal.substring(currentLineStart + indentLength, input.value.length);
input.selectionStart = selStartPos - self.indent.length;
input.selectionEnd = selStartPos - self.indent.length;
}
} else {
input.value = inputVal.substring(0, selStartPos) + self.indent +
inputVal.substring(selStartPos, input.value.length);
input.selectionStart = selStartPos + self.indent.length;
input.selectionEnd = selStartPos + self.indent.length;
}

highlightCode.innerHTML = input.value.replace(/&/g, "&")
.replace(/</g, "&lt;")
Expand Down