Search code examples
shellvimlilypond

Run shell script from Vim with currently open file as argument


I've just started using Vim.

Here is a shell script which I use frequenty from within BBedit.

#!/bin/sh

filename=$(basename "${BB_DOC_PATH##*/}" .ly)
directory=${BB_DOC_PATH%/*}/

cd "${directory}"

lilypondPDFoutput="${directory}"$filename".pdf"

/Applications/Lilypond.app/Contents/Resources/bin/  lilypond -dno-point-and-click -ddelete-intermediate-    files "$BB_DOC_PATH"

wait

open "${lilypondPDFoutput}"

BB_DOC_PATH is a variable which represents the path of the currently open file. (e.g. /Users/me/Documents/file.ly)

How would I go about placing this script in my .vimrc, and invoking it with simple command like :typeset?

Note: I am typesetting a Lilypond file.


Solution

  • The OP asked how to place the script in the .vimrc. This gets just a little tricky because of the odd way Vim import files do line continuation. It would be something like this:

    command Typeset call Typeset()
    fun Typeset()
        let $TYPESET_PATH = expand("%:p")
        let $TYPESET_ROOT = expand("%:p:r")
        let $TYPESET_DIR = expand("%:p:h")
        !sh -icx '
        \ cd "${TYPESET_DIR}"
        \; lilypondPDFoutput="${TYPESET_ROOT}.pdf"
        \; /Applications/Lilypond.app/Contents/Resources/bin/lilypond -dno-point-and-click "$TYPESET_PATH"
        \; wait
        \; open "${lilypondPDFoutput}"
        \'
    endfun
    

    Here's what is actually now working for me in quite a different environment (Lilypond/Win32; Vim for Cygwin).

    " Quick compile command for Lilypond.
    command Typeset call Typeset()
    fun Typeset()
      let $TS_NAME = expand("%:t")
      let $TS_DIR = expand("%:p:h")
      let $TS_PDF = expand("%:t:r") . ".pdf"
      !sh -icx ' cd "${TS_DIR}" && lilypond "${TS_NAME}" && cygstart "${TS_PDF}" '
    endfun
    

    Notes: Lilypond/Win32 does not understand forward-slash paths. Therefore I eliminated the path in its argument. You could do the same. You have already set the path with "cd". Also for my environment I took out the point and click option, as well as the "wait", and changed "open" to "cygstart". At that point the shell part was short enough I did not need the rather arcane line continuation demanded by Vim. At the same time I added shortcut operators so that an error at any stage would stop the process.