/BracketHighlighter/bh_plugin.py

https://bitbucket.org/thomazrb/sublime-text-2 · Python · 142 lines · 80 code · 27 blank · 35 comment · 14 complexity · 3b37bb384d29b3a6d2695659dc521e77 MD5 · raw file

  1. import sublime
  2. from os.path import normpath, join
  3. import imp
  4. from collections import namedtuple
  5. import sys
  6. import traceback
  7. import warnings
  8. class BracketRegion (namedtuple('BracketRegion', ['begin', 'end'], verbose=False)):
  9. """
  10. Bracket Regions for plugins
  11. """
  12. def move(self, begin, end):
  13. """
  14. Move bracket region to different points
  15. """
  16. return self._replace(begin=begin, end=end)
  17. def size(self):
  18. """
  19. Get the size of the region
  20. """
  21. return abs(self.begin - self.end)
  22. def toregion(self):
  23. """
  24. Convert to sublime region
  25. """
  26. return sublime.Region(self.begin, self.end)
  27. def is_bracket_region(obj):
  28. """
  29. Check if object is a BracketRegion
  30. """
  31. return isinstance(obj, BracketRegion)
  32. class ImportModule(object):
  33. @classmethod
  34. def import_module(cls, module_name, loaded=None):
  35. # Pull in built-in and custom plugin directory
  36. if module_name.startswith("bh_modules."):
  37. path_name = join(sublime.packages_path(), "BracketHighlighter", normpath(module_name.replace('.', '/')))
  38. else:
  39. path_name = join(sublime.packages_path(), normpath(module_name.replace('.', '/')))
  40. path_name += ".py"
  41. if loaded is not None and module_name in loaded:
  42. module = sys.modules[module_name]
  43. else:
  44. with warnings.catch_warnings(record=True) as w:
  45. # Ignore warnings about plugin folder not being a python package
  46. warnings.simplefilter("always")
  47. module = imp.new_module(module_name)
  48. sys.modules[module_name] = module
  49. source = None
  50. with open(path_name) as f:
  51. source = f.read().replace('\r', '')
  52. cls.__execute_module(source, module_name)
  53. w = filter(lambda i: issubclass(i.category, UserWarning), w)
  54. return module
  55. @classmethod
  56. def __execute_module(cls, source, module_name):
  57. exec(compile(source, module_name, 'exec'), sys.modules[module_name].__dict__)
  58. @classmethod
  59. def import_from(cls, module_name, attribute):
  60. return getattr(cls.import_module(module_name), attribute)
  61. class BracketPlugin(object):
  62. """
  63. Class for preparing and running plugins
  64. """
  65. def __init__(self, plugin, loaded):
  66. """
  67. Load plugin module
  68. """
  69. self.enabled = False
  70. self.args = plugin['args'] if ("args" in plugin) else {}
  71. self.plugin = None
  72. if 'command' in plugin:
  73. plib = plugin['command']
  74. try:
  75. module = ImportModule.import_module(plib, loaded)
  76. self.plugin = getattr(module, 'plugin')()
  77. loaded.add(plib)
  78. self.enabled = True
  79. except Exception:
  80. print 'BracketHighlighter: Load Plugin Error: %s\n%s' % (plugin['command'], traceback.format_exc())
  81. def is_enabled(self):
  82. """
  83. Check if plugin is enabled
  84. """
  85. return self.enabled
  86. def run_command(self, view, name, left, right, selection):
  87. """
  88. Load arguments into plugin and run
  89. """
  90. plugin = self.plugin()
  91. setattr(plugin, "left", left)
  92. setattr(plugin, "right", right)
  93. setattr(plugin, "view", view)
  94. setattr(plugin, "selection", selection)
  95. setattr(plugin, "nobracket", False)
  96. edit = view.begin_edit()
  97. self.args["edit"] = edit
  98. self.args["name"] = name
  99. try:
  100. nobracket = False
  101. plugin.run(**self.args)
  102. left, right, selection, nobracket = plugin.left, plugin.right, plugin.selection, plugin.nobracket
  103. except Exception:
  104. print "BracketHighlighter: Plugin Run Error:\n%s" % str(traceback.format_exc())
  105. view.end_edit(edit)
  106. return left, right, selection, nobracket
  107. class BracketPluginCommand(object):
  108. """
  109. Bracket Plugin base class
  110. """
  111. def run(self, bracket, content, selection):
  112. """
  113. Runs the plugin class
  114. """
  115. pass