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:
Expand|Select|Wrap|Line Numbers
- 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)+';';}});
- }
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