Template code cleanup

Some parts of special character escaping functions was refactored to get
more readable and consistent code. Rest of this commit consists mostly
from Haddock comment updates.