David Farrell
David Farrell

Reputation: 457

Vim: vsplit and run external command

I'm trying to map a command or function that splits a new window vertically, switches the cursor to the new window, and runs an external command on the <cWORD>.

When I do:

:vsplit|wincmd w|execute '!perldoc <cWORD>'

Vim seems to run the the external command first in the current window and then when the command exits, Vim creates a new window and switches focus to it.

If I break these commands up into separate lines in a function and call the function, the same thing happens. Is there a way to have Vim do what I want it to do?

Upvotes: 1

Views: 852

Answers (2)

David Farrell
David Farrell

Reputation: 457

My coworker Tye showed me how to do it:

let w=expand("<cWORD>") | vnew | execute "read !perldoc " . w|1

  • Save <cWORD> as variable w
  • vnew opens a new empty window
  • execute read !perldoc passing w as the variable. The output is read into the new window
  • Jump to the first line of the buffer in the new window

Upvotes: 1

romainl
romainl

Reputation: 196576

  1. If you don't tell Vim otherwise, new vertical windows open on the left by default, leaving the cursor in the new window.

    :vsplit

    If that's not what you experience you should definitely investigate why.

  2. After :vsplit, further commands are executed before the new window is rendered, in what you can imagine as a "virtual window".

    This means that, however unsettling it can be, you won't see the new window before the next command. That's how Vim works and there's nothing you can do about it.

    In the example below…

    • I have two perl files in the same directory,
    • in perl.pl there's a sample perl script I found online,
    • in warnings.pl there's a single word, warnings,
    • perl.pl is open in Vim with the cursor on strict,
    • I run :vsplit|!perldoc <cWORD>,
    • I expect to see the documentation on strict in my pager and the same buffer displayed in two vertical windows when I come back to Vim,
    • I close the left window,
    • I run :vsplit warnings.pl|!perldoc <cWORD>,
    • I expect to see the documentation on warnings in my pager and two different buffers displayed in two vertical windows when I come back to Vim.

    Let's see:

    :vsplit2

    Looks like everything worked as expected.

  3. I don't see any but you probably have a good reason for opening that new window. I will suggest :help K and :help 'keywordprg anyway:

    set keywordprg=perldoc
    

Upvotes: 0

Related Questions