Skip to content

Instantly share code, notes, and snippets.

@iahu
Last active November 10, 2015 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iahu/ef477739fd7712a60b16 to your computer and use it in GitHub Desktop.
Save iahu/ef477739fd7712a60b16 to your computer and use it in GitHub Desktop.
function getLeftMarkIndex (codeStr, idx) {
var leftCS = codeStr.slice(0, idx);
var leftMarkIdx;
var rOpenMark = /[\[\{\(]/;
var rCloseMark = /[\]\}\)]/;
var matchMarks = /([\[\{\(]|[\]\}\)])/;
var matchMap = {']': '[', '}': ']', ')': '('};
var unpairedCount = 0;
for (var i = leftCS.length - 1; i >= 0; i--) {
var c = leftCS[i];
var match = c.match(matchMarks);
var leftChar = leftCS[i-1];
if (!match) {
continue;
}
if (leftChar === '\\') {
continue;
}
if ( match[0].match(rCloseMark) ) {
unpairedCount++;
continue;
} else if (match[0].match(rOpenMark)) {
unpairedCount--;
if (unpairedCount < 0) {
leftMarkIdx = i;
break;
}
}
}
return leftMarkIdx;
}
function getCloseMarkIndex (codeStr, leftMarkIndex) {
var matchMap = {'[': ']', '{': '}'};
var openMark = codeStr[leftMarkIndex];
var closeMark = matchMap[openMark];
var rightCS = codeStr.slice(leftMarkIndex+1);
var rOpenMark = /[\[|{]/;
var rCloseMark = /[\]|}]/;
var rightMarkIdx, lastMatch;
var unpairedCount = 0;
for (var i = 0; i < rightCS.length; i++) {
var c = rightCS[i];
var leftChar = rightCS[i-1];
if (leftChar === '\\') {
continue;
}
if ( c === openMark ) {
unpairedCount++;
continue;
} else if ( c === closeMark ) {
unpairedCount--;
if ( unpairedCount < 0 ) {
rightMarkIdx = i;
lastMatch = c;
break;
}
}
}
return rightMarkIdx ? (leftMarkIndex + rightMarkIdx + 1) : null;
}
function getBlockRange (codeStr, cursorPos) {
var l = getLeftMarkIndex(str, i);
var r = getCloseMarkIndex(str, l);
if (l && r) {
return {
start: l,
end: r
};
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment