How do I run a Vim command in a restricted sandbox to prevent side effects?
Answer
:sandbox {cmd}
Explanation
The :sandbox command modifier executes any Ex command in a restricted environment where potentially dangerous operations are blocked. This is especially useful when sourcing untrusted vimrc files, running modeline commands, or testing scripts you did not write. Sandboxed commands cannot write files, execute shell commands, modify environment variables, or change certain security-sensitive options.
How it works
:sandbox— the command modifier that enables the restricted execution environment{cmd}— any Ex command to run within the sandbox
Inside the sandbox, Vim blocks operations including:
:!{shell_cmd}— shell command execution:write,:saveas— file writingsystem(),readfile(),writefile()— file and shell function calls:setfor options like'shell','makeprg','grepprg'— security-sensitive optionsautocmdcreation
Example
Source an untrusted vimrc safely:
:sandbox source /tmp/untrusted.vim
If the script tries to run a shell command, Vim will abort with:
E48: Not allowed in sandbox
Evaluate an expression from a modeline safely:
:sandbox let result = eval(untrusted_expr)
Tips
- Vim automatically uses
:sandboxfor modeline processing — this is why modelines cannot execute shell commands - Use
:sandboxwhen writing plugins thateval()orexecuteuser-provided strings - If you need to test what a script does before trusting it,
:sandbox sourceis your first line of defense