Sublime Forum

Custom "save file" command

#1

Hello,

I want to use SublimeText to edit remote files which is accessible only through tsh (teleport). I cant use rmate as tsh does not support remote port forwarding. So i have an idea to use:

  • tsh ssh user@server cat /file_to_edit - command output to get file i want to edit remotely
  • echo "$content" | tsh ssh user@server "cat > /file_to_edit" - command to save it back

So this is my open_file function:

def open_file(server, user, file):
    try:
        content = subprocess.check_output([f'/usr/local/bin/tsh ssh {user}@{server} "cat {file}"'], shell=True)
    except subprocess.CalledProcessError as e:
        sublime.error_message(f"Error: {e}")
        return
    view = self.window.new_file()
    view.set_name(f"{user}@{server}:{file}")
    view.settings().set("auto_indent", False)
    view.settings().set("file_opened_with_custom_command", True)
    view.run_command("insert", {"characters": content.decode()})

I am trying to use my custom command to save file to remote server in case content was changed before close the sublime view:

class RemEditEventListener(sublime_plugin.EventListener):
    def on_pre_close(self, view):
        if view.settings().get("file_opened_with_custom_command"):
            user_server, file = view.name().split(":")
            content = view.substr(sublime.Region(0, view.size()))
            if view.is_dirty:
                choice = sublime.yes_no_cancel_dialog(f"Save?\n{user_server}\n{file}")
                if choice == 1:
                    print("SAVE file && CLOSE sublime view")
                    command = f'/usr/local/bin/tsh ssh {user_server} "cat > {file}"'
                    try:
                        subprocess.Popen(command, shell=True, stdin=subprocess.PIPE).communicate(input=content.encode())
                    except subprocess.CalledProcessError as e:
                        sub.error_message(f"Error: {e}")
                    return
                elif choice == 2:
                    print("do NOT SAVE file && CLOSE sublime view")
                    return
                else:
                    print("do NOT SAVE file && do NOT CLOSE sublime view")
                    return False

Issue is that it pops me up the default “Save, Not save, Cancel” window before my custom one.

Question: is it proper way to override “save” action? And should i do this in on_pre_close?

Thanks in advance

0 Likes