How Apheleia handles asynchronous formatting and cursor stability
mainApheleia solves the responsiveness and cursor-jumping issues common with 'format-on-save' by using the following approach:
- Asynchronous Execution: It runs formatters on the
after-save-hookrather thanbefore-save-hook. It performs the operation asynchronously and only applies changes if the buffer has not been modified since the formatting process started. - RCS Patch Application: Instead of replacing the buffer content directly, it generates an RCS patch of the changes. This prevents changes in other parts of the buffer from moving your cursor (point).
- Smart Point Adjustment: If a patch affects the cursor's position, Apheleia uses a dynamic programming algorithm (Needleman–Wunsch) to calculate the new position so the cursor remains in the same place relative to its surroundings. It also adjusts scroll positions across all windows displaying the buffer to maintain visual continuity.