You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写脚本实现Vim中恒定速度自动重写文件并录制分屏终端?

自动在Vim中以恒定速度重写文件的解决方案

问题根源

你之前的尝试失败原因:

  • 用xdotool时,vim file.txt && xdotool key i的&&会等Vim退出后才执行xdotool,根本没在Vim运行时操作。
  • PyAutoGUI脚本的问题是未确保Vim窗口聚焦,且Vim启动后未等待就绪就执行后续操作,导致输入跑到终端而非Vim里。

方案一:改进xdotool脚本

这个脚本会启动Vim、等待加载、聚焦窗口,再逐个字符输入文件内容:

#!/bin/bash

if [ $# -ne 1 ]; then
    echo "用法: $0 <文件名>"
    exit 1
fi

TARGET_FILE="$1"

# 后台启动Vim
vim "$TARGET_FILE" &
VIM_PROC=$!

# 等待Vim加载完成(根据系统性能调整时间)
sleep 0.5

# 激活Vim窗口(匹配窗口标题,若标题格式不同需修改)
xdotool search --name "$TARGET_FILE" windowactivate

# 进入插入模式
xdotool key i

# 逐个字符输入文件内容,间隔100毫秒(可修改delay值)
while IFS= read -r -n1 char; do
    xdotool type --delay 100 "$char"
done < "$TARGET_FILE"

# 保存退出Vim
xdotool key Escape
xdotool type ":x"
xdotool key Return

# 等待Vim进程结束
wait $VIM_PROC

使用说明:

  1. 保存为vim_type.sh,赋予执行权限:chmod +x vim_type.sh
  2. 运行:./vim_type.sh file.txt
  3. 若窗口标题匹配失败,可改用xdotool search --class Vim windowactivate直接匹配Vim进程窗口。

方案二:改进PyAutoGUI脚本

确保Vim窗口聚焦,等待加载完成后再模拟输入:

import pyautogui
import time
import sys

if len(sys.argv) != 2:
    print("用法: python3 script.py <文件名>")
    sys.exit(1)

file_path = sys.argv[1]

# 预留时间让你聚焦终端窗口
print("3秒内点击终端窗口使其成为活动窗口...")
time.sleep(3)

# 启动Vim
pyautogui.write(f"vim {file_path}")
pyautogui.press("enter")

# 等待Vim加载
time.sleep(0.5)

# 进入插入模式
pyautogui.press("i")
time.sleep(0.1)

# 读取文件并逐个字符输入,间隔0.1秒
with open(file_path, 'r') as f:
    for char in f.read():
        pyautogui.write(char)
        time.sleep(0.1)

# 保存退出
pyautogui.press("esc")
time.sleep(0.1)
pyautogui.write(":x")
pyautogui.press("enter")

进阶优化:如果需要自动定位Vim窗口,可安装pygetwindow库(pip install pygetwindow),替换等待加载后的代码:

# 替换原有time.sleep(0.5)之后的内容
import pygetwindow as gw
time.sleep(0.5)
# 定位并激活Vim窗口
vim_windows = gw.getWindowsWithTitle(file_path)
if vim_windows:
    vim_windows[0].activate()
    time.sleep(0.1)
pyautogui.press("i")
time.sleep(0.1)

方案三:纯Vim脚本实现(最可靠)

无需外部工具,直接用Vim自身功能模拟输入:
创建simulate_type.vim脚本:

" 清空当前缓冲区内容
normal! ggVGd
" 进入插入模式
startinsert
" 读取目标文件内容,逐个字符插入,间隔100毫秒
for line in readfile(argv(0))
    for char in split(line, '\zs')
        call feedkeys(char, 'n')
        sleep 100m
    endfor
    call feedkeys("\<CR>", 'n')
    sleep 100m
endfor
" 退出插入模式并保存退出
normal! :x<CR>

使用方式:

vim -S simulate_type.vim file.txt

这个方案完全在Vim内部执行,不需要窗口聚焦,稳定性最高。

内容的提问来源于stack exchange,提问作者Aner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 02:24:57