FG

How to ignore an autocmd in vim's undo history?

Freshabout 19 hours ago
Mar 15, 2026336 views
Confidence Score0%
0%

Problem

I have the following autocommand, which basically strips whitespace at the end of each line. Unfortunately, at each save, it inserts a step into the undo to jump to the beginning to the file, which is quite annoying. Is there a way to make vim ignore jumping around in the following command, so that…

Error Output

autocmd BufWritePre *
    \ let s:bufwritepre_currline = line('.') |
    \ let s:bufwritepre_currcol = col('.')   |
    \ silent %s/\s*$//           …

Unverified for your environment

Select your OS to check compatibility.

1 Fix

Canonical Fix
Unverified Fix
New Fix – Awaiting Verification

Prevent Undo Steps from Autocommand in Vim

Medium Risk

When the autocommand is triggered on buffer write, the substitution command (`%s/\s*$//`) modifies the buffer and causes Vim to create an undo step for the cursor movement, which includes jumping to the beginning of the file. This behavior is due to the way Vim tracks changes in the buffer, including cursor position.

Awaiting Verification

Be the first to verify this fix

  1. 1

    Modify Autocommand to Use 'silent!'

    Change the autocommand to use 'silent!' instead of 'silent' to suppress the output of the command without affecting the undo history.

    vim
    autocmd BufWritePre * silent! %s/\s*$//
  2. 2

    Use 'let' to Store Cursor Position

    Store the current cursor position before running the substitution command, and restore it afterward to prevent the jump from being recorded in the undo history.

    vim
    let s:bufwritepre_currline = line('.') | let s:bufwritepre_currcol = col('.') | silent! %s/\s*$// | call cursor(s:bufwritepre_currline, s:bufwritepre_currcol)
  3. 3

    Test the Autocommand

    After modifying the autocommand, test it by saving a file with trailing whitespace. Ensure that the cursor position remains unchanged and that the undo history does not include an entry for the cursor jump.

  4. 4

    Check Undo History

    Use the ':undolist' command to review the undo history. Verify that there are no additional entries related to the cursor position change after saving the file.

Validation

To confirm the fix worked, save a file with trailing whitespace and ensure that the cursor remains in the same position and that the undo history does not contain any additional entries for the cursor movement.

Sign in to verify this fix

Environment