i feel your pain, as ironically, i am working on this exact problem right now.
i am creating a pseudo textarea from a <pre> tag with the DOM api of a real textarea, independent of markup.
but, it's not easy; i'm about 40 hours in, and still haven't gotten .selectionStart to be set correctly, though it can be get'd just fine...
in short, i think you'll find it much easier to use the native WYSIWYG edit features to add your markup. you can use ranges or document.execCommand.
i have a huge existing set of editing functionality tied up in my existing textarea-based editor, so i am locked into a text based approach.
if you don't have that encumbrance, it's a lot easier to edit html via dom instead of text.
if you have to do it stringy:
i can't post any code from my project.
But, i will tell you that if you have less than a few dozen KB, inserting a special char via DOM-based selection methods, and splitting the .innerHTML or .textContent on that char is the simplest and often the fastest way to get TO the cursor's pos in a string. that's a big hint.
you can also iterate childNodes and count .data.length, but perhaps i've already said to much..
good luck man, it's a challenge.
perhaps a library might provide some heavy lifting, I didn't look but if anyone reading this knows of one, I'd love to check it out.