Could you have the program keep track of how many open braces there are, and then, when there's any kind of change, close them all, and then reopen the ongoing ones?
To get:
This
is indeed a strange idea.
Then, you would have:
Code:
This \textit{is }\textit{\textbf{in}}\textbf{deed} a strange idea.
The downside would be that for properly nested elements, for e.g.:
This
is a more normal sentence.
you'd get:
Code:
This \textit{is a }\textit{\textbf{more}}\textit{ normal} sentence.
rather than the more elegant:
Code:
This \textit{is a \textbf{more} normal} sentence.
But I think that's OK.
I would think you'd want to do something similar for HTML anyway, since overlapping rather than nested tags, such as:
Code:
This <i>is <b>in</i>deed</b> a strange idea.
...although
some browsers may support it, is not considered proper HTML, and is definitely XHTML invalid. (Or at least W3's HTML validator says so.)
and it would be better to have:
Code:
This <i>is </i><i><b>in</b></i><b>deed</b> a strange idea.