質問

I am working on an Sublime Text 3 plugin and I have so far a little script which copy all text from current file to another using three classes :

import sublime, sublime_plugin

# string and new file created
s = 0
newFile = 0

class CreateNewWindowCommand(sublime_plugin.WindowCommand):
    def run(self):
        global s, newFile
        s = self.window.active_view().substr(sublime.Region(0, self.window.active_view().size()))
        newFile = self.window.new_file()

class CopyTextCommand(sublime_plugin.TextCommand):
    def printAChar(self,char,edit):
        self.view.insert(edit, 0, char)

    def run(self, edit):
        global s
        st = list(s)
        for i in st[::-1]:
            self.printAChar(i, edit)

class PrintCodeCommand(sublime_plugin.WindowCommand):
    def run(self):
        self.window.run_command("create_new_window")
        newFile.run_command("copy_text")

the script is running via the PrintCodeCommand first.

I have multiple questions regarding this code :

  1. Is this the 'right' method to do ? Because passing stuff with global variables seems a little dirty.
  2. Is there a way to create a class that can use WindowCommand and TextCommand at the same time ?
  3. the insert command (in CopyTextCommand) insert in the first place, is there a way to append at the end of the file ?

And another one : How can I use sublime.set_timeout() ? Because like this :

# ...
class CopyTextCommand(sublime_plugin.TextCommand):
    def printAChar(self,char,edit):
        sublime.set_timeout(self.view.insert(edit, 0, char) , 1000) 
        # I want to print a char one per second

Or using the time.sleep() command but it doesn't seem to work...

Thanks in advance !

役に立ちましたか?

解決

I'll answer in short here. If you would like more detail, please create separate questions.

  1. No, you can pass arguments to the run command. The run method for CopyTextCommand would look something like def run(self, edit, content).
  2. No, but you can run a text command on the created view rather than passing it around. You can also apply a name or create an arbitrary setting for the purpose of identifying the correct view
  3. Take a look at the documentation (https://www.sublimetext.com/docs/3/api_reference.html). The second argument is an offset.

Bonus: set_timeout expects a call back function. For a one liner like you have, look up lambda in python.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top