Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Smart" text area auto indent

I'm attempting to make an auto-indenting textarea and so far it works with the following code. The problem that I'm having is that I'm currently preventing the default action of pressing enter in order to calculate the tabs in the line, and then inserting the newline afterwards.

This works, but I want to have the default action of the textarea, in that if you hold enter down, it doesn't scroll the textarea until the caret hits the bottom row, and then the scroll bar stays with caret at the bottom row. The current code below keeps the caret in field of vision if used anywhere in the textarea, but it causes content above the caret to scroll up, which is a compromise as the caret no longer disappears. If there is no other solution this will work fine, but I'm hoping there are other ideas.

    var start = this.selectionStart-1;
    var end = this.selectionEnd;
    var sT = this.scrollTop;
    var sH = this.scrollHeight;
    var vH = $(this).height();

    var x = (sH - sT) - vH;

    // Check if hitting enter on the first line as no newline will be found
    if (this.value.lastIndexOf('\n',start)==-1)
     var startSubstr = 0;
    else 
     var startSubstr = this.value.lastIndexOf('\n',start)+1;

    var endFirst = end - startSubstr;

    var valueToScan = this.value.substr(startSubstr,endFirst);
    var count = 0;

    // Count only \t at the beginning of the line, none in the code   
    while (valueToScan.indexOf('\t')!=-1) {
     if (valueToScan.indexOf('\t')!=0)
      break;
     count++;
     valueToScan = valueToScan.substr(valueToScan.indexOf('\t')+1);
    }

    // Command to isert the newline, and then add the \t's found in previously  
    $(this).insertAtCaret('\n');
    for (var i=0;i<count;count--) {
     $(this).insertAtCaret('\t');
    }  

    var sH = this.scrollHeight;
    this.scrollTop = (sH - x) - vH;

EDIT As an update, to clear away any confusion, I'm attempting to create an IDE style textbox, so for example in most IDEs if you type the following

function example(whatever) {
     Example Stuff // And then hit enter here

I want it to take you to the same tab distance from the left border as "Example Stuff" in order to keep your code easier to read. I currently have that functionality but the problem is that I am intercepting the enter key, which means I have to then provide that functionality. I'm having difficulty replicating the exact functionality of not scrolling the textbox until the cursor hits the bottom border. So, if you were to hold enter at the top of the textarea, the cursor just scrolls down the textarea, moving any text with it until it hits the bottom border, and then the scrollbar for the textarea will follow the cursor. Make sense?

EDIT 2 Updated tags to indicate code is with PHP

I've been working on this while this post has been sitting. I think another option that I'm going to explore when I get a chance is rather than preventing enter just allow the default action of hitting enter and read the string from lastIndexOf('\n')-1 to the most recent \nfor any \t. I think that would give me the string I'm looking for, but without messing up the behavior of the textarea. Will update again after testing.

EDIT 3 Resolved, as per my previous update I decided to scan the string after the key is pressed, preserving the natural behavior (section changed added below for those interested) and the only problem that really remains is that if you hold enter, it won't count the indentation from the origin of the enter press, which is fine by me. I'm going to give this one to http://stackoverflow.com/users/15066/matyr'>matyr, although I did figure out before he responded he was still the closest.

if (this.value.lastIndexOf('\n',start-2)==-1) {
 var startSubstr = 0;
} else {
 var startSubstr = this.value.lastIndexOf('\n',start-1)+1;
}    
var valueToScan = this.value.substr(startSubstr,start);
like image 419
Robert Avatar asked Oct 25 '22 09:10

Robert


2 Answers

I want to have the default action of the textarea

How about binding to keyup instead of keydown/keypress and insert the tab after native line break?

the scroll bar stays with caret at the bottom row

You can preserve the scroll position by restoring scrollTop.

<!DOCTYPE html>
<title>autoindent example</title>
<textarea id="TA" rows="8"></textarea>
<script>
document.getElementById('TA').addEventListener('keyup', function(v){
  if(v.keyCode != 13 || v.shiftKey || v.ctrlKey || v.altKey || v.metaKey)
    return;
  var val = this.value, pos = this.selectionStart;
  var line = val.slice(val.lastIndexOf('\n', pos - 2) + 1, pos - 1);
  var indent = /^\s*/.exec(line)[0];
  if(!indent) return;
  var st = this.scrollTop;
  this.value = val.slice(0, pos) + indent + val.slice(this.selectionEnd);
  this.selectionStart = this.selectionEnd = pos + indent.length;
  this.scrollTop = st;
}, false);
</script>
<p>(not considering IE here)
like image 106
matyr Avatar answered Nov 15 '22 05:11

matyr


Have you ever noticed how the Stack Overflow textareas handle code? If you type:

function example(whatever) {
    Example Stuff // And then hit enter here
}

At first, nothing will happen. Then, when you indent (either by typing or by clicking the 101010 button), it puts a different background on the code. Then, after you wait a short while, it syntax colors the code. But if you start typing again, it goes back to black/white.

I think a similar approach might work for you. Instead of trying to tie everything to the enter keypress event, what you should do is:

  1. Hookup a normal onKeySomething event, but don't just look for "enter"; after every keypress:

    1A. Set some some global variable (eg. timer) to new Date();

    1B. setTimeout(X, timeoutFunction) where X is however long you want to wait after the user stops typing

  2. Create timeoutFunction; this function should check the global "timer" variable and if new Date() - timer > X trigger actualFunction()

  3. actualFunction can then parse the textarea's contents, indent things however you like, and nothing will interrupt the normal flow of things for the user

I know this isn't quite how "real" IDE's behave, but given the limitations of JS and the web, it may well be the best approach for you.

like image 40
machineghost Avatar answered Nov 15 '22 05:11

machineghost