Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vim

autocmd

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.

like image 723
Liang Avatar asked Oct 18 '11 16:10

Liang


1 Answers

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>
like image 156
sidyll Avatar answered Sep 21 '22 12:09

sidyll