0

My path is something like /home/me/projects/project_name/the_part/i_wanna/keep.yestheextensiontoo

I wrote this fuction:

function! CurrentPath()
  let filepath = expand("%")
  let spl = split(filepath, '/')
  let short = spl[4:-1]
  let newpath = join(short, '/')
  return newpath 
endfunction

I want to pass the resulting trimmed path the_part/i_wanna/keep.yestheextensiontoo to a sudo command

I would like to have something like this working:

nnoremap <F4> :w !sudo bin/test CurrentPath()<CR>

Ideally similar to how rspec-vim works where you run the command in a console (that replaces your vim session) and then when you hit enter (after the command is executed) you go back to your vim session.

svlasov
  • 9,923
  • 2
  • 38
  • 39
  • Why do you have `:w` in the mapping? Do you want `bin/test` to generate a file name and then write it? – svlasov Jul 05 '23 at 18:32
  • w was product of trying different things I didn't understand and was not needed as I wanted the exactly opposite behavior (not to run in same window) – Jose Piccioni Jul 14 '23 at 17:19

1 Answers1

1

The mapping:

nnoremap <F4> :w !sudo bin/test CurrentPath()<CR>

After ! everything is passed to the shell with the exception of some special items like % or # (see :help cmdline-special), so you can't really expect CurrentPath() to be evaluated, here.

The simplest way to make this work is to use an "expression mapping", where the whole right-hand-side of the mapping is evaluated at runtime:

nnoremap <expr> <F4> ':w !sudo bin/test ' .. CurrentPath() .. '<CR>'

When you press <F4>, CurrentPath() is evaluated and concatenated with the rest, then the whole thing is sent to your shell.

romainl
  • 186,200
  • 21
  • 280
  • 313
  • Although this works I am still wondering about "(that replaces your vim session) and then when you hit enter (after the command is executed) you go back to your vim session." This command runs the command in the same window. I don't know if I am explaining correctly. The way rspec vim works is your vim gets... minimized? and the command runs taking the whole terminal, then when it finishes you press enter and go back to vim – Jose Piccioni Jul 14 '23 at 17:15
  • nvm, that's exactly what `w` does.... removing the w was enough – Jose Piccioni Jul 14 '23 at 17:18