How do I run a Vim command in sandbox mode to prevent side effects?
Answer
:sandbox {command}
Explanation
Vim's sandbox mode restricts what a command can do, preventing it from executing shell commands, writing files, or modifying certain settings. This is essential for safely evaluating modelines, untrusted code, or testing commands without risk.
How it works
:sandbox {command}— runs the command with restrictions- Blocked operations: shell commands (
:!), file writes,system(),setfenv() - Setting changes are restricted to safe options
- Errors are thrown for blocked operations rather than silently failing
Example
:sandbox !echo dangerous
" Error: E48: Not allowed in sandbox
:sandbox set shell=/bin/evil
" Error: E48: Not allowed in sandbox
:sandbox echo 'safe'
" Works normally: safe
Tips
- Modelines are automatically run in sandbox mode for safety
- Use
sandboxwhen evaluating user-provided expressions or autocmds 'secure'option enables sandbox for all file-local commands- Vim plugins can check
has('sandbox')to detect sandbox mode