If you’ve lost unsaved work in Vim due to a crash or an accidental closing, you can recover unsaved changes using .swp files.

Recovering the Original File from a .swp File in Vim

Launch Vim, from your terminal and Change to the directory where your original file was located. Use the cd command to navigate if needed.

Check for .swp File

Look for a file that starts with .filename.swp (where filename is the name of your original file). Use the ls -a command to view hidden files.

As an alternative, you can list swap files with vim by using the -r or -L option.

Use Vim with the Swap File

When you find the .swp file associated with your original file, use Vim to open the original file along with the swap file for recovery.

vim -r original_file.txt

Replace original_file.txt with the name of your actual file. This command tells Vim to recover using the swap file if applicable.

After executing this command, Vim will detect the swap file and prompt you to recover the changes. You should then proceed with the recovery process within Vim.

Use the Swap-File Recovery

If, for some reason, your original file got deleted, you can open the .swp file in Vim to start the recovery process. Vim will detect the swap file and prompt you to recover. Type :recover and press Enter to initiate the recovery.

Save the Recovered File

After recovering your changes, save the file using :w followed by the file name if needed.

Using .swp files to retrieve saved changes in Vim can be a helpfull when something goes wrong. By following these steps, you can easily recover files if Vim crashes or closes accidentally.

See also: Other posts tagged in Vim Productivity
Vim documentation: Official Vim Documentation

Got any queries or feedback? Feel free to drop a comment below!

Tagged in:

,