4

In order to open PDFs using an external application, one can use the following script:

augroup nonvim
   au!
   au BufRead *.pdf sil exe "!open " . shellescape(expand("<afile>")) | bd  
augroup end

However, this is not optimal, because the pdf would still be loaded into vim, which will take a while if it is large. More importantly, your window layout will be messed up if you have more than one window showing, because of bd.

So, I thought of using BufReadPre instead of using BufRead. This way, I may still be able to cancel reading the file into a buffer. The question is: how?

4

A better option would be BufReadCmd:

                                                        BufReadCmd
BufReadCmd                      Before starting to edit a new buffer.  Should
                                read the file into the buffer. Cmd-event

Since this is supposed to read the file into the buffer, you can just not read it. :)

If you try to do a bd in a BufReadPre autocmd, you'll get an error:

E201: *ReadPre autocommands must not change current buffer

With BufReadCmd:

augroup nonvim
   au!
   au BufReadCmd *.pdf sil exe '!open' shellescape(expand("<afile>")) | bd
augroup end

I don't use a Mac, but replacing open with xdg-open, it worked fairly well enough.

|improve this answer|||||
  • @ultrabowser O.o the advantage of using BufReadCmd is that you aren't reading the file in Vim. – muru Apr 6 '16 at 13:29
  • 1
    @ultrabowser Yes. Vim opens an empty buffer, and then this autocmd is supposed to read the contents of the file. Instead, we just call open, and skip reading the file, and delete the now unnecessary buffer. – muru Apr 6 '16 at 13:35
2

Building on muru's answer, here is a solution that makes opening PDF files through vim seamless. The problem with :bd is that it messes up the window layout, but aside from that you may end up at a completely different buffer than where you opened the PDF from. This uses :b# and then deletes the empty buffer.

One last annoyance - that the buffer is centerd on re-entry - can be fixed with this script. (Use the original version or remove the check for atStartOfFile.)

augroup nonvim
   au!
   au BufReadCmd *.pdf sil exe "!xdg-open " . shellescape(expand("<afile>")) . "&>/dev/null" |
       \ let tobedeleted = bufnr('%') | b# | exe "bd! " . tobedeleted
augroup end

Works with NERDtree.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.