textarea tab

insert tab character in textarea

by Laurens Maneschijn

HTML

<input><br>
<textarea cols="100" rows="10">
a	
	b
		c

</textarea><br>
<input><br>
<hr>
without selection: insert tab at cursor.<br>
with selection: for all lines that the selection covers; insert a tab at the start of line.<br>
(shift-tab to remove one tab from start of lines)<br>

JavaScript

// should work as bookmarklet; just prepend with: `javascript:` and copy paste the rest after it:
// TODO: lots of code cleanup
(function(){
	if(window.textareatabalreadyapplied){
		return;
	}
	window.textareatabalreadyapplied = true;
	
	var allowShiftTab = true;
	var tabChars = '\t';
	
	var target = null;
	var start, end;
	
	window.addEventListener('keydown',function(ev){
		if(ev.keyCode == 9 && ev.target instanceof HTMLTextAreaElement){
			target = ev.target;
			if( target ){
				start = target.selectionStart;
				end   = target.selectionEnd;
				var step = tabChars.length;
				
				target.focus();
				var text = '\n'+target.value.substring(0);
				var ostart = start, oend = end;
				
				// target.selectionEnd kan blijkbaar ook voor target.selectionStart liggen
				if(start>end){var t=end;start=end;start=t;}
				
//				var linestart = start, lineend = end;
//				while(linestart > 0           && text.charAt(linestart) != '\n'){linestart--;}
//				while(lineend   < text.length && text.charAt(lineend)   != '\n'){lineend++;}

				// TODO: shift + noselection : remove tab before cursor instead of at start of line?
				if( allowShiftTab && ev.shiftKey ){
					while(start > 0 && text.charAt(start) != '\n'){start--;}
					end++;	// without this, it cant delete last tab
					if( text.substring(start,end).indexOf(tabChars)!=-1){
						ostart -= (text.substring(start,ostart).indexOf('\n'+tabChars)==-1?0:step);
						oend -= (text.substring(start,end).split('\n'+tabChars).length-1)*step;
						
						text = text.substring(0,start)+text.substring(start,end).
							replace(new RegExp('\\n'+String(tabChars).replace(/\\/g,'\\\\'),'g'),'\n')+
							text.substring(end);
						target.value = text.substring(1);
					}
				}
				else if( !ev.shiftKey ){
							
					ostart+=step;
					if(start==end){
						// nothing selected; just insert a tab character at the current caret position
						oend+=step;
						text =...