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

如何在Gedit插件中检测新文档打开事件?

Gedit插件监听新文档打开的解决方案

针对你遇到的问题——ViewActivatable的do_activate无法覆盖初始空白标签复用加载文档的场景——可以通过以下几种信号实现全面监听:

1. 监听Gedit.Window的active-tab-changed信号

当标签切换(包括初始空白标签加载文档后触发的切换逻辑)时,该信号会被触发。你可以在回调中检查当前标签的文档状态,判断是否是新打开的文档:

  • 对比文档的get_is_untitled()状态,从True变为False时,说明空白标签已加载了实际文档。

2. 监听Gedit.Document的loaded信号

每个文档完成加载(无论是新建标签打开还是复用空白标签)时,都会触发这个信号。为覆盖所有文档,你需要:

  • 在插件激活时,为窗口内已存在的文档连接该信号;
  • 同时监听Gedit.Window的document-added信号,为新添加的文档动态连接loaded信号。

示例代码(基于WindowActivatable扩展点)

from gi.repository import Gedit, GObject

class DocumentOpenMonitor(Gedit.WindowActivatable):
    __gtype_name__ = "DocumentOpenMonitor"
    window = GObject.Property(type=Gedit.Window)

    def do_activate(self):
        # 连接标签切换信号
        self._tab_change_handler = self.window.connect("active-tab-changed", self._on_tab_changed)
        # 为现有文档绑定加载完成信号
        for doc in self.window.get_documents():
            self._bind_document_signals(doc)
        # 监听新添加的文档
        self._doc_add_handler = self.window.connect("document-added", self._on_document_added)

    def do_deactivate(self):
        # 断开信号连接,避免内存泄漏
        self.window.disconnect(self._tab_change_handler)
        self.window.disconnect(self._doc_add_handler)
        for doc in self.window.get_documents():
            doc.disconnect_by_func(self._on_document_loaded)

    def _bind_document_signals(self, doc):
        doc.connect("loaded", self._on_document_loaded)

    def _on_tab_changed(self, window, tab):
        if not tab:
            return
        doc = tab.get_document()
        if not doc.get_is_untitled():
            print(f"检测到文档打开:{doc.get_uri()}")

    def _on_document_loaded(self, doc):
        print(f"文档加载完成:{doc.get_uri()}")

    def _on_document_added(self, window, doc):
        self._bind_document_signals(doc)

为什么ViewActivatable不适用?

Gedit启动时会预先创建一个空白的"未保存文档1"视图,当你在空会话中打开文档时,只是将该视图绑定到新加载的文档,并不会创建新视图,因此ViewActivatable的do_activate不会被触发。而WindowActivatable可以直接从窗口层面监听所有文档和标签的变化,覆盖这种复用场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 14:00:08