Skip to content

Instantly share code, notes, and snippets.

@nexpr
Last active June 18, 2017 11:07
Show Gist options
  • Select an option

  • Save nexpr/bb44663e322f4bff7687994310556b0d to your computer and use it in GitHub Desktop.

Select an option

Save nexpr/bb44663e322f4bff7687994310556b0d to your computer and use it in GitHub Desktop.
indent supporter for textarea.
<!doctype html>
<textarea id="input"></textarea>
<script>
input.onkeydown = function(eve){
if(eve.keyCode === 13){
eve.preventDefault()
var str = this.value
var ss = this.selectionStart
var se = this.selectionEnd
var ls = seekPreLineBeginning(str, ss)
var match = str.slice(ls, ss).match(/^[  \t]*/)
var ins = match && !eve.shiftKey
? "\n" + match[0]
: "\n"
this.value = insertString(removeString(str, ss, se - ss), ss, ins)
this.selectionStart = this.selectionEnd = ss + ins.length
}else if(eve.keyCode === 9){
eve.preventDefault()
var str = this.value
var ss = this.selectionStart
var se = this.selectionEnd
var ls = seekPreLineBeginning(str, ss)
if(eve.shiftKey){
if(str[ls].match(/\s/)){
this.value = removeString(str, ls, 1)
this.selectionStart = Math.max(ls, ss - 1)
this.selectionEnd = Math.max(ls, se - 1)
}
}else{
this.value = insertString(str, ls, "\t")
this.selectionEnd = se + 1
this.selectionStart = ss + 1
}
}
}
function seekPreLineBeginning(str, pos){
while(--pos >= 0 && str[pos] !== "\n"){}
return pos + 1
}
function insertString(base_str, pos, add_str){
return base_str.substr(0, pos) + add_str + base_str.substr(pos)
}
function removeString(base_str, pos, len){
return base_str.substr(0, pos) + base_str.substr(pos + len)
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment