Vim Tips Wiki

Execute a shell command in the directory shown in file explorer

1,612pages on
this wiki

Redirected from VimTip717

Tip 717 Printable Monobook Previous Next

created 2004 · complexity basic · author Chao-Kuo Lin · version 6.0

Even thought I can press "c" to switch directory if I want to execute a command in the directory that I am viewing with the explorer.vim plugin, but sometimes I don't want to actually change to that directory to execute it because I want to remain in whatever directory I am in such as a root directory of source files. So I opened up explorer.vim to see if I can add it directly to the plugin, but I found out that it can call a variable g:explFileHandler that stores the user defined function whenever the key 'x' is pressed on a file or directory. So I used that to implement executing a command in the viewing directory in my vimrc as follows:

function! MyFileHandler(filename)
  let oldpath = getcwd()
  let currentdirectory = ""
    let currentdirectory = strpart(a:filename, 0, strlen(a:filename) - 1)
    let currentdirectory = a:filename
  let lastslash = strridx(currentdirectory, "/")
  let currentdirectory = strpart(currentdirectory, 0, lastslash)
  let usercommand = input(currentdirectory . "# ")
  if(strlen(usercommand) > 0)
    execute "cd " . currentdirectory
    execute "!" . usercommand
    execute "cd " . oldpath
let g:explFileHandler = "MyFileHandler"

It will prompt the user with the directory mimicking a shell prompt where the user can enter the command.


Around Wikia's network

Random Wiki