我在 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 的默认键绑定,并且似乎没有问题。