vimtricks.wiki Concise Vim tricks, one at a time.

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 writing
  • system(), readfile(), writefile() — file and shell function calls
  • :set for options like 'shell', 'makeprg', 'grepprg' — security-sensitive options
  • autocmd creation

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 :sandbox for modeline processing — this is why modelines cannot execute shell commands
  • Use :sandbox when writing plugins that eval() or execute user-provided strings
  • If you need to test what a script does before trusting it, :sandbox source is your first line of defense

Next

How do I use PCRE-style regex in Vim without escaping every special character?