访问Sublime Text 2插件中的快速面板

时间:2012-10-19 14:06:38

标签: python sublimetext2

我正在学习如何创建Sublime Text 2插件。我想做的其中一件事是采取任何突出显示的文本,检查一个网站是否会返回该地址200,然后将一些信息放入快速面板(是的,我知道我应该做的网址在线程中查找,以便它不会阻止主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类,我似乎无法找到任何文档。任何帮助或提示都将非常感激。

1 个答案:

答案 0 :(得分:12)

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

您可以在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