views:

62

answers:

1

I want a simple real-time syntax highlighting in a tinyMce editor. I want to highlight (change background or color of the text) for every #{keyword} and #{more keywords} in the text. Keyword can only contain letters, numbers and dots (.). I don't know if my idea is good:

  • bind to onChange event of the editor
  • remove all occurrences of <span class="code">#{keyword}</span> (regex)
  • find all #{keyword} and replace them with #{found keyword}

(css class code would have background set to some color)

Any ideas how to solve this problem?

+1  A: 

Binding to the onChange event seems ok, but you should consider using the onKey--- events too. I hope the following code snippet will be helpfull for you:

css (to be defined in content_css i.e.):

[current] {
background-color:yellow;
}
[changed] {
background-color:green;
}

js helpfunctions:

var select_current = function(node){
  unselect_current();
  node.setAttribute('current','true');
};

var unselect_current = function(){
  var n = ed.getBody().firstChild;
  while (n){
    if (n.nodeType == 1 && n.getAttribute('current'))
    {
      n.removeAttribute('current');
    }
    n = n.nextSibling;
  }
};

p_of = function(node) // returns p-Element of node
{
  while (node){
  if (node.nodeName == 'BODY') { return null; }
  if (node.nodeName == 'P')    { return node; }
    else { node = node.parentNode; }                    
  }
  return null;
}

on event call:

var _node_changing = false;
console.log('onNodeChange: ', arguments);
if (!_node_changing && element.getAttribute('_mce_type') != 'bookmark'){
  _node_changing = true;
  var p = p_of(element);
  if (p){
    if (!p.getAttribute('current')){
    select_current(p);
    }               
  }
  _node_changing = false;
}
Thariama