4

I have a series of vim commands that write the selected block to a temporary file, run a function (knitcite) on that file, and then read in another file:

w! ~/.vbuf <CR> 
!knitcite ~/.vbuf ~/.vbuf <CR> 
r ~/.vbuf <CR>

If I've selected a block of text in visual mode before running the first command, it becomes

:'<,'>w! ~/.vbuf <CR>

passing the selected contents to the file, as I need. I can put this into a simple vim function in my .vimrc, but cannot figure out how to pass the contents of the visual selection to the function. If this were a single command instead of three commands, I could do this with a visual map, but not sure how to do it with three commands. something like:

command knitcite call Knitcite()
func! Knitcite()  
exec "w! ~/.vbuf <CR>"
exec "!knitcite ~/.vbuf ~/.vbuf <CR> "
exec "r ~/.vbuf <CR>"
func

but this doesn't get any data passed in from the visual block. I guess I need to give an argument to my Knitcite function but cannot figure out what it would be. (Seems that this might be related to this SO question but I couldn't figure out how to generalize from that answer.)

Community
  • 1
  • 1
cboettig
  • 12,377
  • 13
  • 70
  • 113

1 Answers1

3

The simplest thing to do would be to use as a filter:

:'<,'>!knitcite

If knitcite doesn't work in filter mode (often it uses - to signify stdin as a filename, other options may apply) you could wrap it in a shell script:

#!/bin/bash
tmpname="/tmp/$(basename "$0").tmp$RANDOM"

trap "rm -f '$tmpname'" ERR INT EXIT
knitcite <(cat) "$tmpname"
cat "$tmpname"

Otherwise, it looks like you want to replace the visual selection with the output:

:'<,'>w! ~/.vbuf
:'<,'>d _
:silent! !knitcite ~/.vbuf ~/.vbuf.out
:'<-1r ~/.vbuf.out

Note

  1. the use of a separate temporary file for the output: otherwise, trouble may arise on most platforms, where the truncation of the output file might happen before the input has been read!
  2. the use of the black hole register ("_) with the :delete command to avoid clobbering any registers
sehe
  • 374,641
  • 47
  • 450
  • 633
  • Thanks for providing both the direct answer to the question and the suggestion of a better way by wrapping with a shell script. Fantastic. – cboettig Oct 05 '12 at 21:30
  • @cboettig Thanks. Note I just removed superfluous quoting from the signal trap – sehe Oct 05 '12 at 21:34