简体   繁体   中英

vim function external call

Currently my vimrc has the following key mappings:

map <leader>m :w\|!clear && rspec --drb %<cr>
map <leader>k :w\|!clear && rspec --drb %:<C-r>=line('.')<CR><cr>
map <leader>c :w\|:!clear && cucumber --drb -r ./features %<cr>
map <leader>x :w\|!clear && cucumber --drb -r ./features %:<C-r>=line('.')<CR><cr>

However I want to consolidate them into (two) functions that have the same keymap for line vs file, I've tried the following but Vim complains about missing parentheses:

function! TestCurrentLine()
  let spec = '*_spec\.rb'
  if !(expand("%") =~ spec)
    :!clear && cucumber --drb -r ./features %:<C-r>=line('.')<CR>
  else
    :!clear && rspec --drb %:<C-r>=line('.')<CR>
  end
endfunction

function! TestCurrentFile()
  let spec = '*_spec\.rb'
  if !(expand("%") =~ spec)
    :!clear && cucumber --drb -r ./features %
  else
    :!clear && rspec --drb %
  end
endfunction

map <leader>m :w\|call TestCurrentFile<cr>
map <leader>k :w\|call TestCurrentLine<cr>

Any ideas?

apart from the missed () in your map command. Your functions have some problems too:

  • !clear you don't need the leading :
  • '*_spec\\.rb' is supposed to be a regex. but the leading * doesn't make any sense. you want to have .*_spe..... ? also better with .*_spec\\.rb$'
  • pass % directly to your shell command is not 100% safe. (if your buffer name has special chars or spaces). you could use the build-in shellescape() function. For example, shellescape(@%,1) (then you need "execute" to execute the command)
  • consider to create those mapping only for certain filetype (via autocmd) in certain buffer ( <buffer> ), also when creating mapping, consider "nore".

Add parentheses to your function calls:

map <leader>m :w\|call TestCurrentFile()<cr>
map <leader>k :w\|call TestCurrentLine()<cr>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM