Patchou, can you add the ability to get previous messages using the ChatWnd::HistoryText command. So rather than getting a certain text range/length, get a certain number of messages.
See this thread for a bit more info
The best way to do what you want to do is keep every message received in lists in your own script. This way, you can keep everything the way you want and do the optimisations you judge appropriate for your feature.