c# - Highlighting matching brackets in code -
i've wanted write own portable ide clisp while , have started it, using c#.
i have implemented bracket highlighting checking if current character bracket , moving backwards/forwards throughout text, whilst keeping track of following opening/closing brackets until number of opening , closing brackets equal.
i have done using simple loops (also "break"-ing loop matching bracket found), method slow on larger blocks of code. method of highlighting text in richtextbox seems bit inefficient, i.e. selecting characters programmatically moving cursor , applying highlight, deselecting , moving cursor's original position. moving away brackets requires highlighting cleared, select text , remove formatting on it.
occasionally application can't keep track of cursor supposed if user moves cursor fast (using arrow keys on keyboard) , application might erroneously move previous position. put, highlighting function wrote can't keep if user scrolls through large blocks of code using keyboard.
is there more efficient way of going other loops? using inefficient methods highlight , un-highlight brackets? regex offer solution here?
while wrote piece of code myself, in essence have done bill lizard has done here: how find position of matching parentheses or braces in given piece of text?
i believe regex not here - in case, slower, since still has go through code char char.
however, there "simple" solution - create tree of code blocks in code, , update needed when user changes code (ideally, not on every keypress, if done well, option). no longer have find next bracket every time move cursor - know in code block (simple lookup index), , know starting , ending bracket of code is.
the approach assumes updating block indices easy - , really, kind of is; if block before cursor updates, don't change it. if it's after cursor, add numberofcharsinserted
indices. simple , fast. becomes tricky add , remove new blocks of code, gives visual studio trouble :))
another interesting solution might variant of "space partitioning". split code sections can index (for example, binary tree or hash table). if remember number of opening , closing brackets in each of these sections, can quite determine bracket you're looking located, , based on section granularity, can reduce have search.
there's lot of ways optimize searching, @ point, have go through file start end. based on typical use-cases, have choose proper way. in case, believe remembering indices of brackets in file far easiest solution, , it's pretty fast (how many characters brackets out of code? adding 1
hundred indices lot faster searching through thousand chars. , have while changing code!). although did lisp, didn't you? lot of brackets! :d
Comments
Post a Comment