When pasting content in Vim, formatting issues (such as messed-up indentation or unexpected comment symbols) usually occur due to automatic indentation, smart indentation, or improper mishandling of paste mode. Here’s how to fix it:
Method 1: Use “Paste Mode” before pasting
Vim’s paste mode temporarily disables auto-indentation, syntax-based indentation, and other features, ensuring pasted content retains its original formatting.
- In Vim’s normal mode, run:vim
:set pasteYou’ll see-- INSERT (paste) --at the bottom, indicating paste mode is active. - Press
ito enter insert mode, then paste your content (e.g., useCtrl+Vor right-click to paste from the system clipboard). - After pasting, turn off paste mode:vim
:set nopaste
Method 2: Temporarily disable indentation
If you prefer not to use paste mode, disable indentation features temporarily:
- In normal mode, run:vim
:set noautoindent nosmartindent - Press
ito enter insert mode and paste your content. - To restore indentation later (optional, for subsequent editing):vim
:set autoindent smartindent
Method 3: Paste using Vim registers (avoid clipboard interference)
For content copied within Vim, use Vim registers to preserve formatting:
- Copy with
"+y(copy to system clipboard) or"*y(copy to primary clipboard). - Paste with
"+p(paste from system clipboard) or"*p(paste from primary clipboard).
Summary: Method 1 (paste mode) is the most recommended—it’s simple and reliably prevents formatting issues. Just remember to enable paste before pasting and disable it with nopaste afterward.
