Python sublime_plugin 模块,TextCommand() 实例源码

我们从Python开源项目中,提取了以下20个代码示例,用于说明如何使用sublime_plugin.TextCommand()

项目:VHDL-Mode    作者:Remillard    | 项目源码 | 文件源码
def run(self, edit):
        """Standard TextCommand Run method"""
        # Get the current point.
        region = self.view.sel()[0]
        original_point = region.begin()
        point_r, point_c = self.view.rowcol(original_point)
        # Figure out if any tab characters were used.
        line = self.view.substr(self.view.line(original_point))
        numtabs = line.count('\t')
        # Get the current tab size
        tabsize = util.get_vhdl_setting(self, 'tab_size')
        # Create string of correct amount of dashes.  A tab consumed
        # one character but generates tabsize-1 space.
        line = '-'*(80-point_c-(tabsize-1)*numtabs)
        num_chars = self.view.insert(edit, original_point, line)
        print('vhdl-mode: Inserted comment line.')

#----------------------------------------------------------------
项目:VHDL-Mode    作者:Remillard    | 项目源码 | 文件源码
def run(self, edit):
        """Standard TextCommand Run method"""
        # Get the current point.
        region = self.view.sel()[0]
        original_point = region.begin()
        point_r, point_c = self.view.rowcol(original_point)
        # Figure out if any tab characters were used.
        line = self.view.substr(self.view.line(original_point))
        numtabs = line.count('\t')
        # Get the current tab size
        tabsize = util.get_vhdl_setting(self, 'tab_size')
        # Create string of correct amount of dashes.  A tab consumed
        # one character but generates tabsize-1 space.
        line = '-'*(80-point_c-(tabsize-1)*numtabs)
        # Create snippet object.
        snippet = line + '\n' + '-- $0' + '\n' + line + '\n'
        # Inserting template/snippet
        self.view.run_command("insert_snippet",
            {
                "contents" : snippet
            })

#----------------------------------------------------------------
项目:VHDL-Mode    作者:Remillard    | 项目源码 | 文件源码
def run(self, edit):
        '''
        Standard TextCommand Run Method
        '''
        print('Preference Settings')
        print('vhdl-mode: {}: {}'.format('tab_size', util.get_vhdl_setting(self, 'tab_size')))
        print('vhdl-mode: {}: {}'.format('translate_tabs_to_spaces', util.get_vhdl_setting(self, 'translate_tabs_to_spaces')))
        vhdl_settings = sublime.load_settings('vhdl_mode.sublime-settings')
        keys = ['vhdl-user',
                'vhdl-company',
                'vhdl-project-name',
                'vhdl-platform',
                'vhdl-standard',
                'vhdl-modified-time-string',
                'vhdl-use-copyright-block',
                'vhdl-use-revision-block',
                'vhdl-copyright-block',
                'vhdl-revision-block']
        print('Package Settings')
        for key in keys:
            print('vhdl-mode: {}: "{}"'.format(key, vhdl_settings.get(key)))

        print('View Settings')
        for key in keys:
            print('vhdl-mode: {}: {}'.format(key, util.get_vhdl_setting(self, key)))
项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
def error_command(method):
    """
    A decorator that executes method only if the current view has errors.

    This decorator is meant to be used only with the run method of
    sublime_plugin.TextCommand subclasses.

    A wrapped version of method is returned.

    """

    def run(self, edit, **kwargs):
        vid = self.view.id()

        if vid in persist.errors and persist.errors[vid]:
            method(self, self.view, persist.errors[vid], persist.highlights[vid], **kwargs)
        else:
            sublime.status_message('No lint errors.')

    return run
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
def error_command(method):
    """
    A decorator that executes method only if the current view has errors.

    This decorator is meant to be used only with the run method of
    sublime_plugin.TextCommand subclasses.

    A wrapped version of method is returned.

    """

    def run(self, edit, **kwargs):
        vid = self.view.id()

        if vid in persist.errors and persist.errors[vid]:
            method(self, self.view, persist.errors[vid], persist.highlights[vid], **kwargs)
        else:
            sublime.status_message('No lint errors.')

    return run
项目:FancyWord    作者:EastonLee    | 项目源码 | 文件源码
def __init__(self, view):
        sublime_plugin.TextCommand.__init__(self, view)
        s = sublime.load_settings("FancyWord.sublime-settings")
        self.topn = int(s.get('topn', 10))
        self.lang = s.get('language', 'eng')
        self.word2vec_setting = s.get('word2vec', {})
        self.word2vec_enabled = self.word2vec_setting.get('enabled', False)
        self.word2vec_python_path = self.word2vec_setting.get(
            'python_path', 'python')
        self.word2vec_model = self.word2vec_setting.get(
            'pretrained_word2vec_model', '')
        self.word2vec_port = self.word2vec_setting.get('port', 5000)
        self.wordnet_enabled = s.get('wordnet', {}).get('enabled', True)
        # when word2vec-api server is dead, restart it
        if self.word2vec_enabled and not is_word2vec_api_server_running():
            # ['/usr/local/bin/python', '/Users/easton/Downloads/word2vec-api/word2vec-api.py', '--model', '~/Downloads/deps.words.bin', '--binary', 'true']
            print('FancyWord: word2vec-api server is starting')
            word2vec_api_file_path = os.path.join(
                package_folder, 'dependences/word2vec-api.py')
            self.word2vec_api_command = [self.word2vec_python_path, word2vec_api_file_path,
                                         '--model', self.word2vec_model,
                                         '--binary', 'true',
                                         '--port', str(self.word2vec_port)]
            print(' '.join(self.word2vec_api_command))
            start_subproc(self.word2vec_api_command)
项目:NeoVintageous    作者:NeoVintageous    | 项目源码 | 文件源码
def _view(self):
        """Return the view that should receive any actions."""
        view = None
        try:
            view = self.view
        except AttributeError:
            try:
                view = self.window.active_view()
            except AttributeError:
                raise AttributeError(
                    'ViCommandMixin must be used with a TextCommand or a WindowCommand class')
        return view
项目:NeoVintageous    作者:NeoVintageous    | 项目源码 | 文件源码
def _window(self):
        """Return the view that should receive any actions."""
        window = None
        try:
            window = self.window
        except AttributeError:
            try:
                window = self.view.window()
            except AttributeError:
                raise AttributeError(
                    'ViCommandMixin must be used with a TextCommand or a WindowCommand class')
        return window
项目:VHDL-Mode    作者:Remillard    | 项目源码 | 文件源码
def run(self):
        """Sublime TextCommand run method"""
        # Assigning this to a string to keep command shorter later.
        template = "Packages/VHDL Mode/Snippets/vhdl-testbench.sublime-snippet"

        tb_view = self.window.new_file()
        tb_view.assign_syntax('Packages/VHDL Mode/Syntax/VHDL.sublime-syntax')
        tb_view.set_name('{}_tb.vhd'.format(_interface.name))

        entity_name = '{}_tb'.format(_interface.name)
        signals_str = _interface.signals()
        constants_str = _interface.constants()
        instance_str = _interface.instance(name="DUT")

        # Inserting template/snippet
        tb_view.run_command("insert_snippet",
            {
                "name"     : template,
                "ENAME"    : entity_name,
                "CONSTANTS": constants_str,
                "SIGNALS"  : signals_str,
                "INSTANCE" : instance_str
            })
        tb_view.run_command("vhdl_mode_insert_header")
        print('vhdl-mode: Created testbench from interface.')

#----------------------------------------------------------------
项目:SublimeRemoteGDB    作者:summerwinter    | 项目源码 | 文件源码
def run(self):
        global g_show_errors
        g_show_errors = True
        update_all_views(self.window)

# class ErrorsClick(sublime_plugin.TextCommand):
#     def run(self, edit):
#         if not g_error_views.is_open():
#             return
#         row, col = self.view.rowcol(self.view.sel()[0].a)
#         if g_error_views.is_open() and self.view.id() == g_error_views.get_view().id():
#             g_error_views.select(row)
#     def is_enabled(self):
#         return g_error_views.is_open()
项目:NoDialogs    作者:maximsmol    | 项目源码 | 文件源码
def __init__(self, view):
        self.last_change_count = None
        self.completions = None
        self.completions_count = None
        self.last_completion_index = None

        sublime_plugin.TextCommand.__init__(self, view)
项目:.sublime    作者:cxdongjack    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        sublime_plugin.TextCommand.__init__(self, *args, **kwargs)

        self.settings = sublime.load_settings('termX.sublime-settings')
        self.paths = []
        self.debug_info = {}
项目:sublime-single-trailing-new-line    作者:mattst    | 项目源码 | 文件源码
def on_pre_save(self, view):
        """ Called immediately before the file in the view is saved. """

        if self.is_plugin_enabled(view):
            # A TextCommand derived class is needed to get an edit object.
            view.run_command("single_trailing_new_line")
项目:VintageousPlus    作者:trishume    | 项目源码 | 文件源码
def __init__(self, view):
        sublime_plugin.TextCommand.__init__(self, view)
项目:VintageousPlus    作者:trishume    | 项目源码 | 文件源码
def __init__(self, view):
        sublime_plugin.TextCommand.__init__(self, view)
项目:VintageousPlus    作者:trishume    | 项目源码 | 文件源码
def _view(self):
        '''
        Returns the view that should receive any actions.
        '''
        view = None
        try:
            view = self.view
        except AttributeError:
            try:
                view = self.window.active_view()
            except AttributeError:
                raise AttributeError(
                    'ViCommandMixin must be used with a TextCommand or a WindowCommand class')
        return view
项目:VintageousPlus    作者:trishume    | 项目源码 | 文件源码
def _window(self):
        '''
        Returns the view that should receive any actions.
        '''
        window = None
        try:
            window = self.window
        except AttributeError:
            try:
                window = self.view.window()
            except AttributeError:
                raise AttributeError(
                    'ViCommandMixin must be used with a TextCommand or a WindowCommand class')
        return window
项目:py-search    作者:vieira-rafael    | 项目源码 | 文件源码
def updatePos(view): #print 'updatepos' view.settings().set('origPos',view.viewport_position())
def initialize(view): #print 'initialize' if not view.settings().has('syncScroll'):     view.settings().set('syncScroll',False) #the add on change should be here, it's elsewhere for debug reasons updatePos(view) view.settings().clear_on_change('syncScroll') #for debug reasons    view.settings().add_on_change('syncScroll', updateStatus) #when syncScroll is toggled, update status bar    settings = sublime.load_settings('Sync View Scroll.sublime-settings')   status_off = settings.get('status_off') if status_off:      view.set_status('syncScroll', status_off)def plugin_loaded(): if not 'running_synch_scroll_loop' in globals(): global running_synch_scroll_loop     running_synch_scroll_loop = True        _thread.start_new_thread(synch_scroll_loop, ()) #on startup initialize every view print ("syncScroll starting") for window in sublime.windows(): for view in window.views():            initialize(view)def synch_scroll_loop(): while True: global synch_scroll_running if not synch_scroll_running:           synch_scroll_running = True         sublime.set_timeout(lambda: synch_scroll(), 0)      time.sleep(0.08)def synch_scroll(): global synch_scroll_running global synch_scroll_current_view_object # print ("one timeout") current_view = synch_scroll_current_view_object if current_view is None or current_view.is_loading() or not current_view.settings().get('syncScroll'):      synch_scroll_running = False return callingViewPosX, callingViewPosY = current_view.viewport_position() origCallingViewPosX, origCallingViewPosY = current_view.settings().get('origPos') # print ('modified. origCallingViewPos=', origCallingViewPosX, origCallingViewPosY, 'callingViewPos= ', callingViewPosX, callingViewPosY) if callingViewPosX != origCallingViewPosY or callingViewPosY != origCallingViewPosY: #and it moved vertically or horizontally # print ("it moved") for view in current_view.window().views(): if view.settings().get('syncScroll') and view.id() != current_view.id(): #if view has syncScroll enabled AND we're not talking about the same view as view #we move view              viewPosX, viewPosY = view.viewport_position()               newViewPosX = viewPosX+callingViewPosX-origCallingViewPosX              newViewPosY = viewPosY+callingViewPosY-origCallingViewPosY # print ("moving. viewPos= ",viewPosX,viewPosY," newViewPos= ",newViewPosX,newViewPosY)              view.set_viewport_position((newViewPosX,newViewPosY), True) #move the other view                updatePos(view)     updatePos(current_view) #update original positions  synch_scroll_running = False
def updateStatus(): # print "updateStatus"  settings = sublime.load_settings('Sync View Scroll.sublime-settings') for window in sublime.windows(): for view in window.views(): if view.settings().get('syncScroll'):                status_on = settings.get('status_on') if status_on:                 view.set_status('syncScroll', status_on) else:              status_off = settings.get('status_off') if status_off:                  view.set_status('syncScroll', status_off) else:                 view.erase_status('syncScroll')
class syncScrollListener(sublime_plugin.EventListener): def on_activated(self, view): global synch_scroll_current_view_object       synch_scroll_current_view_object = view     view.settings().set('origPos', view.viewport_position()) def on_load(self,view): #on load add settings to a view # print ("on_load")        initialize(view) def on_text_command(self, current_view, command_name, args): if current_view.settings().get('syncScroll') and command_name == 'move_to' and args['to'] in ['bof', 'eof']: for view in current_view.window().views(): if view.settings().get('syncScroll') and view.id() != current_view.id():                  view.run_command(command_name, args)
class ToggleSyncScrollCommand(sublime_plugin.TextCommand): def run(self, edit):     current_state = self.view.settings().get('syncScroll') self.view.settings().set('syncScroll',not current_state) def is_checked(self): if not self.view.settings().has('syncScroll'):            initialize(self.view)
项目:Sublime-Eval    作者:ViktorQvarfordt    | 项目源码 | 文件源码
def terminate(self):
        self.terminated_user = True
        if self.proc:
            p = self.proc
            self.proc = None
            p.kill()
            p.communicate()




## This is here for future reference.
# class EvalLatexMathematicaReplace(sublime_plugin.TextCommand):
#     def run(self, edit):
#         for sel in self.view.sel():
#             if sel.begin() == sel.end():
#                 region = self.view.line(sel)
#             else:
#                 region = sel
#             code = self.view.substr(region)
#             try:
#                 p = subprocess.Popen(
#                     'math -run \'Print[TeXForm[ToExpression["%s", TeXForm]]]; Exit[]\'' % code.replace('\\', '\\\\'),
#                     shell=True,
#                     stdout=subprocess.PIPE,
#                     stderr=subprocess.STDOUT,
#                     bufsize=1,
#                     universal_newlines=True)
#                 p.wait()
#                 output = p.stdout.read()
#                 # Hack to compensate for not being able to use -noprompt, since -noprompt causes ToExpression to hang.
#                 output = '\n'.join(output.split('\n')[2:])
#             except Exception as e:
#                 output = 'ERROR: %s' % str(e)
#             if output:
#                 self.view.replace(edit, region, output)
项目:CrystalAutoComplete    作者:TechMagister    | 项目源码 | 文件源码
def on_query_completions(self, view, prefix, locations):
        # Check if this is a Crystal source file. This check
        # relies on the Crystal syntax formatting extension
        # being installed - https://github.com/crystal-lang/sublime-crystal
        if view.match_selector(locations[0], "source.crystal"):

            try:
                raw_results = run_cracker(view, locations[0])
            except FileNotFoundError:
                print("Unable to find cracker executable (check settings)")
                return

            results = []
            regexp = '[\.#](.+)\('

            for r in raw_results:
                if r.type == "Function":
                    if r.name.find("#") != -1:
                        trigger = r.name.split("#")[1]
                    else:
                        trigger = r.name.split(".")[1]
                    contents = trigger.split("(")[0]

                    if r.name.find("()") == -1:
                        contents = contents + '('
                else:
                    trigger = r.name
                    contents = r.name
                results.append([trigger, contents])

            if len(results) > 0:
                # return results
                return (results, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)


#class CrystalGotoDefinitionCommand(sublime_plugin.TextCommand):
#    def run(self, edit):
#        # Get the buffer location in correct format for cracker
#        row, col = self.view.rowcol(self.view.sel()[0].begin())
#        row += 1
#
#        results = run_cracker(self.view, ["find-definition", str(row), str(col)])
#
#        if len(results) == 1:
#            result = results[0]
#            path = result.path
#            # On Windows the cracker will return the paths without the drive
#            # letter and we need the letter for the open_file to work.
#            if sublime.platform() == 'windows' and not re.compile('^\w\:').match(path):
#                path = 'c:' + path
#            encoded_path = "{0}:{1}:{2}".format(path, result.row, result.column)
#            self.view.window().open_file(encoded_path, sublime.ENCODED_POSITION)