6

我正在学习如何创建 Sublime Text 2 插件。我想做的一件事是获取任何突出显示的文本,检查网站是否会在该地址返回 200,然后将一些信息放入快速面板(是的,我知道我应该做 url在线程中查找,以免阻塞主 UI)。目前我有:

import sublime
import sublime_plugin
import urllib2

class CheckUrlPanel(sublime_plugin.WindowCommand):

def quick_panel(self, messages, flags):
    self.window.show_quick_panel(messages, None, flags)

class CheckUrlsCommand(sublime_plugin.TextCommand):

def run(self, edit):
    urls = []
    selections = self.view.sel()
    for selection in selections:
        urls.append(self.view.substr(selection))

    messages = self.validate_urls(urls)
    panel = CheckUrlPanel()
    panel.quick_panel(messages, sublime.MONOSPACE_FONT)

def validate_urls(self, urls):
    messages = []
    for url in urls:
        try:
            request = urllib2.Request(url, headers={ "User-Agent" : "Sublime URL Checker" }) 
            response = urllib2.urlopen(request, timeout=3)
            message = '"%s" is a valid URL.' % url
        except Exception as (e):
            message = '"%s" is an invalid URL.' % url

        messages.append(message)

    return messages

我得到的错误是:

Traceback (most recent call last):
File "./sublime_plugin.py", line 362, in run_
File "./CheckUrls.py", line 19, in run
  panel = CheckUrlPanel()
  TypeError: __init__() takes exactly 2 arguments (1 given)

问题是我不知道如何正确初始化 WindowCommand 类,而且我似乎找不到任何文档。任何帮助或提示将不胜感激。

4

1 回答 1

12

您不需要创建另一个实例WindowCommand来完成此操作。顺便说一句,您通常会编写命令,但不会在插件中创建它们的实例。它们通过键绑定或run_commandView/Window/sublime 的方法实例化和调用。

您可以在check_urls命令处理程序中获取当前活动窗口并显示一个快速面板。

window = sublime.active_window()
window.show_quick_panel(messages, None, sublime.MONOSPACE_FONT)

这是一个完整的来源:

import sublime
import sublime_plugin
import urllib
from urllib.request import urlopen

class CheckUrlsCommand(sublime_plugin.TextCommand):

   def run(self, edit):
      urls = []
      selections = self.view.sel()
      for selection in selections:
         urls.append(self.view.substr(selection))

      messages = self.validate_urls(urls)
      window = sublime.active_window()
      window.show_quick_panel(messages, None, sublime.MONOSPACE_FONT)

   def validate_urls(self, urls):
      messages = []
      for url in urls:
         try:                
            response = urlopen(request, timeout=3)
            message = '"%s" is a valid URL.' % url
         except Exception as e:
            message = '"%s" is an invalid URL.' % url

         messages.append(message)

      return messages
于 2012-10-22T14:01:08.127 回答