Vim automatic scroll buffer

2019-07-21 22:29发布

问题:

I'm trying to do something very simple:

I have two buffers in Vim, one with source code (B1), another one with a text file a.txt (B2). The source code in B1 is run with a custom shortcut in Vim, filling a.txt with text. I want Vim to automatically scroll B2 every time it updates, even if my cursor is in B1. So, I just want that the buffer B2 to behave the way tail -f does.

Doing this with ConqueTerm is not an option, since buffer B2 can be a preview buffer from other plugin.

回答1:

In general, vim events fire in response to user input. They don't just run continuously in the background.

This post details some tricks you could repurpose to write some customization code to reload your "tail -f" buffer and scroll to the bottom periodically.

Rather than trying to do this all in vim, here is a different proposal that would achieve a similar effect using GNU Screen (one terminal area with vim editing a file file1, another running tail -f against a different file file2):

  • download/install GNU Screen (perhaps apt-get install screen)
  • run screen
  • run vim file1
  • type Ctrl-A S to split the terminal down the middle horizontally (or, in recent versions of screen, Ctrl-A | to split it down the middle vertically)
  • type Ctrl-A Tab to switch to the other side of the split
  • type Ctrl-A c to start a new terminal on this side
  • run tail -f file2

Now one side of the split shows vim file1 and the other side shows tail -f file2. Here's an image of the result.



回答2:

This command moves to the window containing a.txt, reloads it (edit), moves to the end (+$) and then jumps back to the previous window. You can add it to the shortcut that runs your source code to get a.txt to update whenever the code is run.

:exe bufwinnr("a.txt") . "wincmd w" | edit +$ | exe winnr("#") . "wincmd w"

Remember to escape the bars (\|) and add a <CR> at the end if you use this in a mapping.

This will require your shortcut to run the code in foreground, and Vim will be unresponsive till it is done (unless you press Ctrl-C). If you want Vim to reload a.txt automatically whenever it is changed (thus bypassing the need for running the code in foreground), you will need an external mechanism for file change detection (such as inotifywait on Linux). As far as I know, Vim only checks for external changes (with autoread) when you move the cursor to that window.