TransWikia.com

how to use variables in vimscript shell commands

Vi and Vim Asked by alec on December 30, 2020

I have this code intended to:

  1. read current line
  2. extract variable from end of line, looking for text like #ad04e482
  3. search for filename that begins with the string ad04e482
  4. open that file to edit in vim
  5. bind this to a few keystrokes <leader>tn

I’m struggling to define and use these variables inside the execute function calls…

function TaskSearch()
  let line = getline('.')
  let task_id = split(line, "#")[1]
  let task_note = execute('find ~/.task/notes/ -name "task_id*"')
  execute('edit ~/.task/notes/$task_note')
endfunction
command! TaskSearch :call TaskSearch()
nnoremap <leader>tn :TaskSearch <Enter>

I’ve tried many different variatlions of the let task_note... and execute(...) statements without any success.

I’ve looked through various posts on the stack network but I haven’t seen any examples using a vimscript variable (like task_id in my case) inside a shell command’s arguments.

I need to take the results of that command, which should be just a single file, and then open that file in a new buffer to edit it. How can I achieve this?

One Answer

Here's one way that works...

function! TaskSearch()
  ..snip...
  let task_note = system('find ~/.task/notes -name "' . task_id . '"*')
  exe 'e ' . task_note
endfunction

Call with :call TaskSearch().

Some of the key changes...

  1. Escaping of glob (*) in the find call.
  2. Use of system() which is a vim function that returns result of executing external processes.
  3. Use of Ex commands rather than function(s) to open the file, i.e. using exe and e[dit].
  4. find should return a full path so there shouldn't be a need to repeat ~/.task/notes in the exe line.

Might need a little fine tuning to get it to work for your exact problem (e.g. this isn't controlling for a scenario where find returns more than one file...make sure your query is specific/explicit enough to prevent that or use additional shell commands to narrow it down, if needed). Let me know if you have any problems or questions about how it works.

An important point is that when you want to include the value of a variable in a command you usually need to use something like exe, i.e. something that will treat its arguments as an expression to be evaluated.

Correct answer by B Layer on December 30, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP