public int FindMatchingBracketBackward(AvaloniaEdit.Document.TextDocument document, int startOffset, char close, char open) { var result = startOffset; var currentChar = document.GetCharAt(startOffset--); if (currentChar == close) { var numOpen = 0; while (true) { if (startOffset < 0) { break; } currentChar = document.GetCharAt(startOffset--); if (currentChar == open && numOpen == 0) { result = startOffset + 1; break; } if (currentChar == close) { numOpen++; } else if (currentChar == open) { numOpen--; } if (startOffset >= document.TextLength) { break; } } } return(result); }