Vim Tips Wiki
(codelisting readjusted)
m (Executing shell command in Explorer's current viewing directory moved to Execute a shell command in the directory shown in file explorer: Page moved by JohnBot to improve title)

Revision as of 09:49, 18 October 2007

Previous TipNext Tip

Tip: #717 - Execute a shell command in the directory shown in file explorer

Created: May 13, 2004 12:25 Complexity: basic Author: Chao-Kuo Lin Version: 6.0 Karma: 4/1 Imported from: Tip#717

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 = "" 
  if(isdirectory(a:filename)) 
    let currentdirectory = strpart(a:filename, 0, strlen(a:filename) - 1) 
  else 
    let currentdirectory = a:filename 
  endif 
  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 
  endif 
endfunction 
"
let g:explFileHandler = "MyFileHandler" 

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

Comments