Minor reorganization.
Refactored key handlers.
Made the logic more modular, hopefully easier to follow,
and removed repeated code.
Plus, some optimization in RichString code.