cgram: fix assertion when substituting at the end of the longest line
Reported by Weitian LI via GitHub.
Contrary to the patch suggested in [1], still allow the cursor to be
placed to the very right of the text in a line since that is the usual
behavior of text editors.
Split the function substitute() into two parts: one that handles the
curses-specific part of checking whether a substitution is possible at
the current cursor position, and one that performs the actual
substitution. Only the latter is kept in the code section for the
string manipulation functions, the other is moved to the section for
curses code. Having all the curses code in one place reduces the places
that call beep(). Previously, as well as now, there is a single beep
per invalid key before, but that was not obvious from the previous code.
[1]: https://github.com/DragonFlyBSD/DragonFlyBSD/commit/
18d09f18cf4c