我正在Sublime Text中制作一个插件,该插件会提示用户输入密码以在文件保存之前对其进行加密。在执行保存之前,已执行的API中有一个钩子,因此我的简单实现是:
class TranscryptEventListener(sublime_plugin.EventListener): def on_pre_save(self, view): # If document is set to encode on save if view.settings().get('ON_SAVE'): self.view = view # Prompt user for password message = "Create a Password:" view.window().show_input_panel(message, "", self.on_done, None, None) def on_done(self, password): self.view.run_command("encode", {password": password})
这样做的问题是,当输入面板出现供用户输入密码时,该文档已经保存(尽管触发器为“ on_pre_save”)。然后,一旦用户点击enter
,文档将被很好地加密,但情况是存在一个保存的纯文本文件,以及一个填充了加密文本的修改后的缓冲区。
因此,在执行保存之前,我需要让Sublime Text等待用户输入密码。有没有办法做到这一点?
目前,加密完成后,我只是手动重新保存:
def on_pre_save(self, view, encode=False): if view.settings().get('ON_SAVE') and not view.settings().get('ENCODED'): self.view = view message = "Create a Password:" view.window().show_input_panel(message, "", self.on_done, None, None) def on_done(self, password): self.view.run_command("encode", {password": password}) self.view.settings().set('ENCODED', True) self.view.run_command('save') self.view.settings().set('ENCODED', False)
但这很麻烦,如果用户取消加密,则将保存纯文本文件,这是不理想的。有什么想法吗?
编辑:我想我可以通过重写默认save
命令来干净地做到这一点。我希望通过使用on_text_command
or on_window_command
触发器来做到这一点,但似乎该save
命令不会触发这两个(可能是应用程序命令?但没有on_application_command
)。难道没有办法覆盖保存功能吗?
编辑:我最终只是重写了与TextCommand的默认键绑定,而且似乎没有问题。