Syntax-Coloring of a textarea

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sandromani
    New Member
    • Dec 2007
    • 16

    Syntax-Coloring of a textarea

    Hi all,
    I am writing a webbased notepad and want to include syntax-coloring. The approach I have used is to set the font color and background color of the textarea to transparent, and place the colored text in a pre behind the text area, so far so good. The code I use for coloring is the following one:

    Code:
    function colorize(){
    	var inTag=false, inAttr=false;
    	text=textarea.text();
    	colorarea.innerHTML=text.substring(0,selection.end).replace(/[(<>"'&]/g,function(m){
    		if(m=='<'){
    			if(inTag){return '&#'+m.charCodeAt(0)+';';}
    			else{inTag=true;return '<span style="color:#0000FF;"><'}}
    		else if(m=='>'){
    			if(!inTag||inAttr){return '&#'+m.charCodeAt(0)+';';}
    			else{inTag=false;return '></span>';}}
    		else if(m=='"'){if(inTag){if(!inAttr){inAttr=true;return '<span style="color:#999900;">"';}else{inAttr=false;return '"</span>';}}else{return '&#'+m.charCodeAt(0)+';';}}
    		else{return '&#'+m.charCodeAt(0)+';';}})+'<img src="style/caret.gif" alt="" id="caret" />'+text.substring(selection.end).replace(/[(<>"'&]/g,function(m){
    		if(m=='<'){inTag=true;return '<span style="color:#0000FF;"><'}
    		else if(m=='>'){inTag=false;return '></span>';}
    		else if(m=='"'){if(inTag){if(!inAttr){inAttr=true;return '<span style="color:#999900;">"';}else{inAttr=false;return '"</span>';}}else{return '&#'+m.charCodeAt(0)+';';}}
    		else{return '&#'+m.charCodeAt(0)+';';}});
    	}
    where I had to emulate the caret with an animated gif because at least firefox makes the caret transparent as soon as the font color is transparent >.<.
    Anyway, as you might guess, it is not really fast, considering the fact that the script is run uppon every key press event... My question, has anyone experience with a more efficient approach? Or just "forget it"?:D

    Thanks for any inputs!
    Cheers,
    Sandro Mani
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    How about execCommand - also see the test page.

    Comment

    • sandromani
      New Member
      • Dec 2007
      • 16

      #3
      Thanks for that link, the contentEditable property was exactly what I needed!

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        You're welcome. Glad it helped :)

        Comment

        Working...