How to open pdf files under cursor (using 'gf') with external PDF readers in vim

2.8k views Asked by At

The current gf command will open *.pdf files as ascii text. I want the pdf file opened with external tools (like okular, foxitreader, etc.). I tried to use autocmd to achieve it like this:

au BufReadCmd *.pdf silent !FoxitReader % & "open file under cursor with FoxitReader
au BufEnter *.pdf <Ctrl-O> "since we do not really open the file, go back to the previous buffer

However, the second autocmd failed to work as expected. I could not figure out a way to execute <Ctrl-o> command in a autocmd way.

Could anyone give me a hint on how to <Ctrl-O> in autocmd, or just directly suggest a better way to open pdf files with gf?

Thanks.

2

There are 2 answers

5
sidyll On

That's because what follows an autocmd is an ex command (the ones beginning with a colon). To simulate the execution of a normal mode command, use the :normal command. The problem is that you can't pass a <C-O> (and not <Ctrl-O>) directly to :normal, it will be taken as literal characters (<, then C, then r) which is not a very meaningful normal command. You have two options:

1.Insert a literal ^O Character

Use controlvcontrolo to get one:

au BufEnter *.pdf normal! ^O

2.Use :execute to Build Your Command

This way you can get a more readable result with the escaped sequence:

au BufEnter *.pdf exe "normal! \<c-o>"

Anyway, this is not the most appropriate command. <C-O> just jumps to the previous location in the jump list, so your buffer remains opened. I would do something like:

au BufEnter *.pdf bdelete

Instead. Still I have another solution for you.


Create another command with a map, say gO. Then use your PDF reader directly, or a utility like open if you're in MacOS X or Darwin (not sure if other Unix systems have it, and how it's called). It's just like double clicking the icon of the file passed as argument, so it will open your default PDF reader or any other application configured to open any file by default, like images or so.

:nnoremap gO :!open <cfile><CR>

This <cfile> will be expanded to the file under the cursor. So if you want to open the file in Vim, use gf. If you want to open it with the default application, use gO.

If you don't have this command or prefer a PDF-only solution, create a map to your preferred command:

:nnoremap gO :!FoxitReader <cfile> &<CR>
1
arcseldon On

If the default app is acceptable, then simply using :!open % in command mode works. You can always map this to a suitable leader combination in your vim config file etc.

If you want something that works with normal mode, then you could try something like the following (i use this too for opening HTML files), and modify to your own needs:

if has('win32') || has ('win64') autocmd FileType html nmap <Leader>g :silent ! start firefox "%"<cr> elseif has('mac') autocmd FileType html nmap <Leader>g :!open "%"<cr><cr> endif