【问题标题】:Passing Element Through Sublime Text 3 Plugin通过 Sublime Text 3 插件传递元素
【发布时间】:2013-11-27 00:17:46
【问题描述】:

我正在开发一个 Sublime Text 3 插件,到目前为止,我有一个小脚本,它使用三个类将所有文本从当前文件复制到另一个:

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")

脚本首先通过 PrintCodeCommand 运行。

我对此代码有多个问题:

  1. 这是“正确”的做法吗?因为使用全局变量传递东西似乎有点脏。
  2. 有没有办法创建一个可以同时使用WindowCommand和TextCommand的类?
  3. 插入命令(在 CopyTextCommand 中)首先插入,有没有办法在文件末尾追加?

还有一个:如何使用 sublime.set_timeout() ?因为像这样:

# ...
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

或者使用 time.sleep() 命令但它似乎不起作用...

提前致谢!

【问题讨论】:

  • 请避免每个问题都问多个问题

标签: python text timeout sublimetext3 sublime-text-plugin


【解决方案1】:

我会在这里简短地回答。如果您想了解更多详细信息,请创建单独的问题。

  1. 不,您可以将参数传递给运行命令。 CopyTextCommand 的运行方法类似于def run(self, edit, content)
  2. 不可以,但是您可以在创建的视图上运行文本命令,而不是传递它。您还可以应用名称或创建任意设置以识别正确的视图
  3. 查看文档 (https://www.sublimetext.com/docs/3/api_reference.html)。第二个参数是偏移量。

奖金: set_timeout 需要回调函数。对于像你这样的单行,在 python 中查找 lambda。

【讨论】:

  • 1.好的,我会试试的。 2. 我不太明白你的回答。 3. 好的,谢谢。对于设置的超时,我将尝试测试并了解如何正确执行。谢谢!
  • 您可以从当前的新窗口命令中调用newView.run_command("copy_text"),而不是使用 3 个单独的命令。如果您真的想将事物分开,您可以使用view.settings().set("some special key", <some value>) 将一些设置应用于新视图并搜索该视图。您也可以将缓冲区命名为 view#set_name 并搜索。
  • 我需要手动进行复制,因为我不会一次复制整个文件,而是想将其临时化。拥有多个类的目的是因为我无法创建一个新文件,并一次操作文件的内部......或者也许使用像 copy_text 这样的 sublime 的内置命令......
  • 也许我不了解您的用例。您可以使用window#active_view 访问当前视图的内容。从那里你可以复制你想要的任何内容。然后,您可以将新的视图对象作为window#new_file 的一部分取回。您将其存储在 newView 变量中。然后您可以使用newView.run_command("copy_text") 运行插入命令。好吧,最终,这取决于你。
猜你喜欢
  • 2014-02-13
  • 1970-01-01
  • 2014-10-11
  • 2018-02-09
  • 2014-04-04
  • 1970-01-01
  • 2013-08-31
  • 2014-10-23
  • 2016-09-22
相关资源
最近更新 更多