Fandom

Vim Tips Wiki

Execute a shell command in the directory shown in file explorer

Redirected from VimTip717

1,624pages on
this wiki
Add New Page
Talk0 Share

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.

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 = ""
  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.

CommentsEdit

Also on Fandom

Random Wiki