Select parentheses inside input field

I am trying to highlight parentheses based on their level, and if they match or not. Thus, the first level gets the next class paren_1 , the second gets paren_2 and so on. I want to highlight the circle of parentheses next to the carriage, if any. If you have a caret next to a parenthesis (openeing or clos), it should highlight the specified bracket and its corresponding. My (broken) implementation of this is shown in the fiddle.

This works pretty well. The problems are as follows:

  • If there is HTML in the input line, everything breaks. I tried to elude html before sending it using jQuery('<div />').text(text).html() , which works, but destroys the caret position.
  • If at the "same level" there are several brackets, and the carriage is next to one set, then more is highlighted than necessary.
  • If there is an inconsistent bracket, it should be highlighted in red or something similar. This doesn't work either, and I don't know how to implement it. I tried my best, but everything failed.

JSFiddle: http://jsfiddle.net/yWzWV/1/

Pay attention to everything: I am not very good at javascript or jquery, so you have to excuse me if this code makes you clear your eyes.

Thanks in advance!

+4
source share
1 answer

The problem is resolved, but I ran into another. Here's the fiddle with corrections: http://jsfiddle.net/Axvgf/

Here's the modified method:

 function colorize(text, pos) { var i = 0, current_times = 0; var startc = '(', endc = ')'; var current = -1; var entities = {'>': '&gt;','<':'&lt;'}; var p2 = 0; var regex = new RegExp(Object.keys(entities).join("|"),'g'); var converted = text.replace(regex, function(x, j) { if(pos > j) p2 += entities[x].length - 1; return entities[x]; }); pos += p2; var parens = [], indices = [], o = {}; var newText = converted.replace(/((?:\\)*)([()])/g, function(full, escape, x, idx) { var len = escape.split(/\\/g).length - 1; if (len % 2 == 0) { indices.push(idx); if (x == startc) ++i; o[idx] = { selected: false, type: x, depth: i, idx: idx, pair: -1, extra: escape }; if (idx == pos) o[idx].selected = true; if (x == startc) parens.push(idx); else { if (parens.length > 0) { var p = parens.pop(); o[idx].pair = p; if (o[p].selected) o[idx].selected = true; o[p].pair = idx; if (o[idx].selected) o[p].selected = true; } --i } } }); newtext = converted; indices = indices.sort(function(x,y) { return Number(y) - Number(x); }); indices.forEach(function(i) { newtext = newtext.substr(0,i) + o[i].extra + "<span class='" + (o[i].pair == -1 ? "unmatched " : "paren_" + (o[i].depth % 5)) + (o[i].selected ? " selected_paren": "") + "'>" + o[i].type + "</span>" + newtext.substr(i + 1 + o[i].extra.length) }); return newtext; } 
+2
source

All Articles