Python sublime.Region() Examples

The following are code examples for showing how to use sublime.Region(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: SublimeKSP   Author: nojanath   File: bbcode.py    GNU General Public License v3.0 6 votes vote down vote up
def run(self, *args, **kwargs):
        view = sublime.active_window().active_view()

        #settings = sublime.load_settings('KSP.sublime-settings')
        #scheme_file = settings.get('color_scheme', 'Packages/SublimeKSP/KScript Light.tmTheme')
        scheme_file = 'Packages/SublimeKSP/KScript Light.tmTheme'
        plist = readPlistFromBytes(sublime.load_binary_resource(scheme_file))

        result = ['[pre]']
        start, end = view.sel()[0].a, view.sel()[0].b
        if start == end:
            start, end = 0, view.size()
        for a, b, scopes in get_ranges(view.scope_name(i) for i in range(start, end)):
            result.append(self.apply_style(scopes, plist, view.substr(sublime.Region(start+a, start+b))))
        result.append('[/pre]')
        sublime.set_clipboard(''.join(result)) 
Example 2
Project: dired   Author: kublaios   File: common.py    MIT License 6 votes vote down vote up
def move(self, forward=None):
        """
        Moves the cursor one line forward or backwards.  Clears all sections.
        """
        assert forward in (True, False), 'forward must be set to True or False'

        files = self.fileregion()
        if files.empty():
            return

        pt = self.view.sel()[0].a

        if files.contains(pt):
            # Try moving by one line.
            line = self.view.line(pt)
            pt = forward and (line.b + 1) or (line.a - 1)

        if not files.contains(pt):
            # Not (or no longer) in the list of files, so move to the closest edge.
            pt = (pt > files.b) and files.b or files.a

        line = self.view.line(pt)
        self.view.sel().clear()
        self.view.sel().add(Region(line.a, line.a)) 
Example 3
Project: TerminalView   Author: Wramberg   File: sublime_terminal_buffer.py    MIT License 6 votes vote down vote up
def _update_line_content(self, edit, line_no, content):
        # Note this function has been optimized quite a bit. Calls to the ST3
        # API has been left out on purpose as they are slower than the
        # alternative.

        # We need to add a newline otherwise ST3 does not break the line
        content_w_newline = content + "\n"

        # Check in our local buffer that the content line is different from what
        # we are already showing - otherwise we can stop now
        view_content_cache = self._sub_buffer.view_content_cache()
        if view_content_cache.has_line(line_no):
            if view_content_cache.get_line(line_no) == content_w_newline:
                return

        # Content is different - make ST3 region that spans the line. Start by
        # geting start and end point of the line
        line_start, line_end = view_content_cache.get_line_start_and_end_points(line_no)

        # Make region spanning entire line (including any newline at the end)
        line_region = sublime.Region(line_start, line_end)
        self.view.replace(edit, line_region, content_w_newline)
        view_content_cache.update_line(line_no, content_w_newline) 
Example 4
Project: TerminalView   Author: Wramberg   File: sublime_terminal_buffer.py    MIT License 6 votes vote down vote up
def _update_line_colors(self, line_no, line_color_map):
        # Note this function has been optimized quite a bit. Calls to the ST3
        # API has been left out on purpose as they are slower than the
        # alternative.
        view_region_cache = self._sub_buffer.view_region_cache()
        view_content_cache = self._sub_buffer.view_content_cache()

        for idx, field in line_color_map.items():
            length = field["field_length"]
            color_scope = "terminalview.%s_%s" % (field["color"][0], field["color"][1])

            # Get text point where color should start
            line_start, _ = view_content_cache.get_line_start_and_end_points(line_no)
            color_start = line_start + idx

            # Make region that should be colored
            buffer_region = sublime.Region(color_start, color_start + length)
            region_key = "%i,%s" % (line_no, idx)

            # Add the region
            flags = sublime.DRAW_NO_OUTLINE | sublime.PERSISTENT
            self.view.add_regions(region_key, [buffer_region], color_scope, flags=flags)
            view_region_cache.add(line_no, region_key) 
Example 5
Project: WrapAsYouType   Author: btrekkie   File: wrap_fixer.py    MIT License 6 votes vote down vote up
def _prev_char_scope(self, point, line_region):
        """Return the scope associated with the character before "point".

        Return the scope associated with the character before "point",
        as in _view.scope_name, but if that is a line break character,
        return None instead.

        In a typical Sublime syntax file, a line-based scope (e.g. a
        comment.line) includes the newline character at the end of the
        line.  This does not seem quite proper to me, but in any event
        it requires special behavior in _matches_selector and
        _point_matches_selector concerning the beginning of the line.
        This is why _prev_char_scope returns None at the beginning of a
        line.

        int point - The point.
        Region line_region - The value of _view.line(point).
        return str - The scope.
        """
        if point > line_region.begin():
            return self._view.scope_name(point - 1)
        else:
            return None 
Example 6
Project: WrapAsYouType   Author: btrekkie   File: wrap_fixer.py    MIT License 6 votes vote down vote up
def _point_matches_selector(self, section, point, line_region):
        """Return whether the specified point matches "section".

        Return whether the specified point matches "section", based on
        section['selector'].

        We should conceive of a match as being performed not on a
        character, but on the point between two characters.  For
        example, in C++ block comments, a selection cursor that is
        immediately before the /* is in the block comment, even though
        the preceding character is not.  Likewise, a selection cursor
        that is immediately after the */ is in the block comment, even
        though the succeeding character is not.

        dict<str, object> section - The section, formatted like the
            elements of _settings_parser.sections.
        int point - The position.
        Region line_region - The value of _view.line(point).
        return bool - Whether the position matches.
        """
        return self._matches_selector(
            section, self._prev_char_scope(point, line_region),
            self._view.scope_name(point)) 
Example 7
Project: MvPageExportImport   Author: ummmmm   File: MvPageExportImport.py    MIT License 6 votes vote down vote up
def do_underline( self, view, items ):
		scope_map 	= {}
		regex		= re.compile( 'file="([^"].+?\.htm)"')

		for region in self.regions:
			view.erase_regions( 'mvpageexportimport_{0}' . format( region ) )

		for item in items:
			line 	= view.substr( sublime.Region( item.a, item.b ) )
			matches	= regex.search( line )

			if not matches:
				continue

			start, end 	= matches.span()
			start 		= item.a + start + 6
			end			= item.a + end - 1

			self.regions.append( item.a )
			view.add_regions( 'mvpageexportimport_{0}' . format( item.a ), [ sublime.Region( start, end ) ], 'dot', flags = sublime.DRAW_SOLID_UNDERLINE | sublime.DRAW_NO_FILL | sublime.DRAW_NO_OUTLINE )

#
# Used by the mouse bindings
# 
Example 8
Project: sublime-text-keybinding-helper   Author: r-stein   File: command_assistant.py    MIT License 6 votes vote down vote up
def run(self, edit, command_name, args=None):
        view = self.view
        width, _ = view.viewport_extent()
        em_width = view.em_width()
        columns = width / em_width

        button_text = " ".join(_BUTTON_TEXTS)
        button_text = " " * (int(columns) - len(button_text) - 3) + button_text
        text = "command: " + command_name
        if args:
            text += "\n   args: " + json.dumps(args)
        text += "\n" + button_text
        text += "\n"
        view.replace(edit, sublime.Region(0, view.size()), text)
        _reset_sel(view)

        # store the information in the view
        vsettings = view.settings()
        vsettings.set("kh_content_length", view.size())
        vsettings.set("kh_command_name", command_name)
        vsettings.set("kh_args", args) 
Example 9
Project: sublime-text-keybinding-helper   Author: r-stein   File: command_assistant.py    MIT License 6 votes vote down vote up
def on_selection_modified_async(self, view):
        if not capturing:
            return
        if not hasattr(self, "output_view"):
            return
        if view != self.output_view:
            return
        if (len(view.sel()) != 1 or
                not view.sel()[0].empty() or
                view.sel()[0].a == 0):
            return
        point = view.sel()[0].b
        word = view.word(point)
        command = view.substr(sublime.Region(word.a - 1, word.b + 1))
        if command in self._button_handler:
            self._button_handler[command](view)

    # -------------------------------------
    # show the commands in the output panel
    # ------------------------------------- 
Example 10
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def on_query_completions(self, view, prefix, locations):
		global py_compl, subl_compl

		if not view.match_selector(locations[0], 'source.python -string -comment -constant'):
			return []
		pt = locations[0] - len(prefix) - 1
		ch = view.substr(sublime.Region(pt, pt + 1))
		is_dot = (ch == '.')
		if not is_dot:
			completions = py_compl				# a reference to py_compl (functions)
		elif view.find("(?:from|import)\s+sublime", 0) is not None:
			completions = subl_compl			# Sublime (.methods)
		else:
			return []
		return (completions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
		# return completions 
Example 11
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def on_post_save(self, view):

        filename = view.file_name()
        ext = os.path.splitext(filename)[1]

        if not ext:
            shebang = view.substr(sublime.Region(0, 2))

            if shebang == '#!':
                mode = os.stat(filename)[stat.ST_MODE]
                mode = mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
                os.chmod(filename, mode)

                self.name = os.path.split(filename)[1]
                sublime.set_timeout(
                    lambda: sublime.status_message(
                        "'{0}' is now executable.".format(self.name)
                    ),
                    4000) 
Example 12
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def on_done(self, index):
        self.quick_panel = None
        win = self.window
        for v, r in reversed(self.rollback):
            if isinstance(r, (Region, Selection)):
                v.sel().clear()
                v.sel().add(r)
                v.show_at_center(r)
            else:
                g, i = r
                win.set_view_index(v, g, i)
        win.focus_view(self.origin_view)
        if index == -1:
            return
        locs = self.locations
        text = self.text
        fpath, fname, rowcol = locs[index]
        r, c = rowcol
        self.jump(fpath, r, c, text) 
Example 13
Project: External-Programs-ST3   Author: Hibou57   File: external_programs.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def erase_view_content(view):
        """ Erase all text in `view`. """
        region = sublime.Region(0, view.size())
        view.sel().add(region)
        view.run_command(S_INSERT, {S_CHARACTERS: ""}) 
Example 14
Project: SublimeKSP   Author: nojanath   File: ksp_plugin.py    GNU General Public License v3.0 5 votes vote down vote up
def compile_handle_error(self, error_msg, error_lineno, error_filename):
        view = CompileKspThread.find_view_by_filename(error_filename, self.base_path)
        if view:
            sublime.active_window().focus_view(view)
            if error_lineno is not None:
                pos = view.text_point(error_lineno, 0)
                line_region = view.line(sublime.Region(pos, pos))
                selection = view.sel()
                view.show(line_region)
                selection.clear()
                selection.add(line_region)
        sublime.status_message('Error - compilation aborted!')
        sublime.error_message(error_msg)
        sublime.status_message('') 
Example 15
Project: SublimeKSP   Author: nojanath   File: ksp_plugin.py    GNU General Public License v3.0 5 votes vote down vote up
def read_file_function(self, filepath):
        if filepath.startswith('http://'):
            from urllib.request import urlopen
            s = urlopen(filepath, timeout=5).read().decode('utf-8')
            return re.sub('\r+\n*', '\n', s)

        if self.base_path:
            filepath = os.path.join(self.base_path, filepath)
        filepath = os.path.abspath(filepath)
        view = CompileKspThread.find_view_by_filename(filepath, self.base_path)
        if view is None:
            s = codecs.open(filepath, 'r', 'utf-8').read()
            return re.sub('\r+\n*', '\n', s)
        else:
            return view.substr(sublime.Region(0, view.size())) 
Example 16
Project: SublimeKSP   Author: nojanath   File: ksp_plugin.py    GNU General Public License v3.0 5 votes vote down vote up
def _extract_completions(self, view, prefix, point):
        # the sublime view.extract_completions implementation doesn't seem to allow for
        # the . character to be included in the prefix irrespectively of the "word_separators" setting
        if '.' in prefix:
            # potentially slow work around for the case where there is a period in the prefix
            code = view.substr(sublime.Region(0, view.size()))
            return sorted(re.findall(re.escape(prefix) + r'[a-zA-Z0-9_.]+', code))
        else:
            #return sorted(view.extract_completions(prefix, point)) # default implementation if no '.' in the prefix
            return view.extract_completions(prefix, point) # default implementation if no '.' in the prefix 
Example 17
Project: SublimeKSP   Author: nojanath   File: ksp_plugin.py    GNU General Public License v3.0 5 votes vote down vote up
def on_query_completions(self, view, prefix, locations):
        # parts of the code inspired by: https://github.com/agibsonsw/AndyPython/blob/master/PythonCompletions.py
        global builtin_compl_vars, builtin_compl_funcs, magic_control_pars
        if not view.match_selector(locations[0], 'source.ksp -string -comment -constant'):
            return []
        pt = locations[0] # - len(prefix) - 1
        #ch = view.substr(sublime.Region(pt, pt + 1))    # the character before the trigger
        line_start_pos = view.line(sublime.Region(pt, pt)).begin()
        line = view.substr(sublime.Region(line_start_pos, pt))    # the character before the trigger

        if re.match(r' *declare .*', line) and ':=' not in line:
            compl = []
        elif re.match(r'.*-> ?[a-zA-Z_]*$', line): # if the line ends with something like '->' or '->valu'
            compl = magic_control_pars
        else:
            compl = self._extract_completions(view, prefix, pt)
            compl = [(item + "\tdefault", item) for item in compl
                     if len(item) > 3 and item not in all_builtins]
            if '.' not in prefix:
                bc = []
                bc.extend(builtin_compl_vars)
                bc.extend(builtin_compl_funcs)
                compl.extend(bc)
        compl = self.unique(compl)

        return (compl, sublime.INHIBIT_WORD_COMPLETIONS |
                sublime.INHIBIT_EXPLICIT_COMPLETIONS) 
Example 18
Project: SublimeKSP   Author: nojanath   File: ksp_plugin.py    GNU General Public License v3.0 5 votes vote down vote up
def run(self, edit, new_text=''):
        self.view.replace(edit, sublime.Region(0,self.view.size()),new_text) 
Example 19
Project: SublimeKSP   Author: nojanath   File: ksp_plugin.py    GNU General Public License v3.0 5 votes vote down vote up
def run(self, edit):
        global last_compiler
        if last_compiler:
            uncompress = last_compiler.uncompress_variable_names
            selections = self.view.sel()
            if len(selections) == 1 and selections[0].empty():
                selections = [sublime.Region(0, self.view.size())]
            for selection in selections:
                code = self.view.substr(selection)
                self.view.replace(edit, selection, uncompress(code)) 
Example 20
Project: SublimeKSP   Author: nojanath   File: ksp_plugin.py    GNU General Public License v3.0 5 votes vote down vote up
def is_probably_ksp_file(self, view):
        ext = os.path.splitext(view.file_name())[1].lower()
        if ext == '.ksp' or ext == '.b3s' or ext == '.nbsc':
            return True
        elif ext == '.txt':
            code = view.substr(sublime.Region(0, view.size()))
            score = sum(sc for (pat, sc) in [(r'^on init\b', 1), (r'^on note\b', 1), (r'^on release\b', 1), (r'^on controller\b', 1), ('^end function', 1), ('EVENT_ID', 2), ('EVENT_NOTE', 2), ('EVENT_VELOCITY', 2), ('^on ui_control', 3), (r'make_persistent', 2), ('^end on', 1), (r'-> result', 2), (r'declare \w+\[\w+\]', 2)]
                        if re.search('(?m)' + pat, code))
            return score >= 2
        else:
            return False 
Example 21
Project: RainbowBrackets   Author: absop   File: main.py    MIT License 5 votes vote down vote up
def remove_brackets(self, edit, select_content=True):
        pairs = [p for p in self.find_cursor_brackets()]
        regions = [r for p in pairs for r in p]

        regions.sort()
        for r in reversed(regions):
            self.view.erase(edit, r)

        if select_content:
            selections = []
            for p in pairs:
                begin = p[0].a - regions.index(p[0])
                end = p[1].a - regions.index(p[1])
                selections.append(sublime.Region(begin, end))
            self.view.sel().add_all(selections) 
Example 22
Project: RainbowBrackets   Author: absop   File: main.py    MIT License 5 votes vote down vote up
def cover(self, left, right):
        return sublime.Region(left.a, right.b) 
Example 23
Project: tachyons-sublime-autocomplete   Author: webchun   File: tachyons_autocomplete.py    GNU General Public License v3.0 5 votes vote down vote up
def on_query_completions(self, view, prefix, locations):

        if view.match_selector(locations[0], "text.html string.quoted"):

            # Cursor is inside a quoted attribute
            # Now check if we are inside the class attribute

            # max search size
            LIMIT  = 250

            # place search cursor one word back
            cursor = locations[0] - len(prefix) - 1

            # dont start with negative value
            start  = max(0, cursor - LIMIT - len(prefix))

            # get part of buffer
            line   = view.substr(sublime.Region(start, cursor))

            # split attributes
            parts  = line.split('=')

            # is the last typed attribute a class attribute?
            if len(parts) > 1 and parts[-2].strip().endswith("class"):
                return self.class_completions
            else:
                return []
        elif view.match_selector(locations[0], "text.html meta.tag - text.html punctuation.definition.tag.begin"):

            # Cursor is in a tag, but not inside an attribute, i.e. <div {here}>
            # This one is easy, just return completions for the data-uk-* attributes
            return self.data_completions

        else:

            return [] 
Example 24
Project: WhooshSearch   Author: rokartnaz   File: WhooshSearch.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self, edit):
        self.view.erase(edit, sublime.Region(0, self.view.size())) 
Example 25
Project: sublime-solium-gutter   Author: sey   File: solium-gutter.py    MIT License 5 votes vote down vote up
def save_buffer_to_temp_file(self):
    buffer_text = self.view.substr(sublime.Region(0, self.view.size()))
    temp_file_name = ".__temp__"
    temp_file_path = PLUGIN_FOLDER + "/" + temp_file_name
    f = codecs.open(temp_file_path, mode="w", encoding="utf-8")
    f.write(buffer_text)
    f.close()
    return temp_file_path 
Example 26
Project: sublime-solium-gutter   Author: sey   File: solium-gutter.py    MIT License 5 votes vote down vote up
def on_quick_panel_selection(self, index):
    if index == -1:
      return

    # Focus the user requested region from the quick panel.
    region = SoliumGutterStore.errors[index][0]
    region_cursor = sublime.Region(region.begin(), region.begin())
    selection = self.view.sel()
    selection.clear()
    selection.add(region_cursor)
    self.view.show(region_cursor) 
Example 27
Project: dired   Author: kublaios   File: prompt.py    MIT License 5 votes vote down vote up
def run(self, edit, completions=None):
        self.view.erase(edit, Region(0, self.view.size()))
        self.view.insert(edit, 0, '\n'.join(completions)) 
Example 28
Project: dired   Author: kublaios   File: common.py    MIT License 5 votes vote down vote up
def fileregion(self):
        """
        Returns a region containing the lines containing filenames.  If there are no filenames
        Region(0,0) is returned.
        """
        count = self.filecount()
        if count == 0:
            return Region(0, 0)
        return Region(self.view.text_point(2, 0), self.view.text_point(count+2, 0)-1) 
Example 29
Project: tailwind-sublime-autocomplete   Author: danklammer   File: tailwind_autocomplete.py    GNU General Public License v3.0 5 votes vote down vote up
def on_query_completions(self, view, prefix, locations):

        if view.match_selector(locations[0], "text.html string.quoted"):

            # Cursor is inside a quoted attribute
            # Now check if we are inside the class attribute

            # max search size
            LIMIT  = 250

            # place search cursor one word back
            cursor = locations[0] - len(prefix) - 1

            # dont start with negative value
            start  = max(0, cursor - LIMIT - len(prefix))

            # get part of buffer
            line   = view.substr(sublime.Region(start, cursor))

            # split attributes
            parts  = line.split('=')

            # is the last typed attribute a class attribute?
            if len(parts) > 1 and parts[-2].strip().endswith("class"):
                return self.class_completions
            else:
                return []
        elif view.match_selector(locations[0], "text.html meta.tag - text.html punctuation.definition.tag.begin"):

            # Cursor is in a tag, but not inside an attribute, i.e. <div {here}>
            return self.data_completions

        else:

            return [] 
Example 30
Project: cs-script-sublime   Author: oleg-shilo   File: cs-script.py    MIT License 5 votes vote down vote up
def run(self, edit, **args):
        parts = args['region'].split(',')
        region = sublime.Region(int(parts[0]), int(parts[1]))
        replacement = args['replacement']
        self.view.replace(edit, region, replacement)

# =================================================================================
# CS-Script resolve missing usings service
# =================================================================================
# DONE 
Example 31
Project: cs-script-sublime   Author: oleg-shilo   File: cs-script.py    MIT License 5 votes vote down vote up
def run(self, edit):
        self.view.hide_popup()
        point = self.view.sel()[0].begin()

        left_char = self.view.substr(point-1)
        right_char = self.view.substr(point)
        line = self.view.line(point)
        line_str = self.view.substr(line)

        new_point = -1

        if line_str.startswith('//css'):
            csscript_show_tooltip(self.view,  line.begin()).do()
            return

        if left_char == ' ' or left_char == '(' or left_char == ',' or right_char == ')':
            new_point = point - 1
            while self.view.substr(new_point) != '(':
                new_point = new_point - 1
                if new_point < line.begin():
                    new_point = -1
                    break

        if new_point != -1:
            hint = self.view.substr(sublime.Region(point, new_point))
            csscript_show_tooltip(self.view,  new_point+1, hint).do()
        else:
            csscript_show_tooltip(self.view,  point).do()

# =================================================================================
# CS-Script references search service
# ================================================================================= 
Example 32
Project: cs-script-sublime   Author: oleg-shilo   File: syntaxer.py    MIT License 5 votes vote down vote up
def run_doc_in_cscs(args, view, handle_line, on_done=None, nuget_warning = True):

    curr_doc = view.file_name()

    clear_and_print_result_header(curr_doc)

    if not path.exists(csscriptApp):
        print('Error: cannot find CS-Script launcher - ', csscriptApp)
    elif not curr_doc:
        print('Error: cannot find out the document path')
    else:

        clear_and_print_result_header(curr_doc)

        if nuget_warning and '//css_nuget' in view.substr(sublime.Region(0, view.size())):
            output_view_write_line(out_panel, "Resolving NuGet packages may take time...")

        def do():
            all_args = [csscriptApp]

            for a in args:
                all_args.append(a)

            all_args.append(curr_doc)

            proc = popen_redirect(all_args)

            first_result = True
            for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"):
                line = line.strip()
                if first_result:
                    first_result = False
                    clear_and_print_result_header(curr_doc)

                handle_line(line)

            if on_done:
                on_done()

        sublime.set_timeout(do, 100)
# ----------------- 
Example 33
Project: cs-script-sublime   Author: oleg-shilo   File: utils.py    MIT License 5 votes vote down vote up
def output_view_write_line(name, text, move_caret_to_end=False):
    view = get_output_view(name) # to ensure it's created
    view.run_command('append', {'characters': text + '\n'})
    if move_caret_to_end:
        view.sel().clear()
        view.sel().add(sublime.Region(view.size(), view.size()))
# ----------------- 
Example 34
Project: cs-script-sublime   Author: oleg-shilo   File: utils.py    MIT License 5 votes vote down vote up
def get_text(view):
    text = view.substr(sublime.Region(0, view.size()))
    if view.line_endings() == 'Windows':
        text = text.replace('\n', '\r\n') #Roslyn on Win expects /r/n but Sublime on Win still operates with /n only
    return text
# ----------------- 
Example 35
Project: TerminalView   Author: Wramberg   File: sublime_terminal_buffer.py    MIT License 5 votes vote down vote up
def run(self, _):
        cursor_pos = self.view.settings().get("terminal_view_last_cursor_pos")
        tp = self.view.text_point(cursor_pos[0], cursor_pos[1])
        self.view.sel().clear()
        self.view.sel().add(sublime.Region(tp, tp)) 
Example 36
Project: TerminalView   Author: Wramberg   File: sublime_terminal_buffer.py    MIT License 5 votes vote down vote up
def _update_cursor(self):
        cursor_pos = self._sub_buffer.terminal_emulator().cursor()
        last_cursor_pos = self.view.settings().get("terminal_view_last_cursor_pos")
        if last_cursor_pos and last_cursor_pos[0] == cursor_pos[0] and last_cursor_pos[1] == cursor_pos[1]:
            return

        tp = self.view.text_point(cursor_pos[0], cursor_pos[1])
        self.view.sel().clear()
        self.view.sel().add(sublime.Region(tp, tp))
        self.view.settings().set("terminal_view_last_cursor_pos", cursor_pos) 
Example 37
Project: TerminalView   Author: Wramberg   File: sublime_terminal_buffer.py    MIT License 5 votes vote down vote up
def run(self, edit, start=0, end=None):
        if end is None:
            end = self.view.size()

        self.view.set_read_only(False)
        region = sublime.Region(start, end)
        self.view.erase(edit, region)
        self.view.set_read_only(True) 
Example 38
Project: LuaFormat   Author: floydawong   File: LuaFormat.py    MIT License 5 votes vote down vote up
def run(self, edit):
        # check whether the lua files
        suffix_setting = self.view.settings().get('syntax')
        file_suffix = suffix_setting.split('.')[0]
        if file_suffix[-3:].lower() != 'lua': return

        # get lines of replacement
        r = sublime.Region(0, self.view.size())
        self.view.unfold(r)
        
        # get characters of view
        lines = []
        for region in self.view.lines(r):
            cache = self.view.substr(region)
            if len(cache) == 0: cache = ' '
            lines.append(cache)

        # get cursor position before the replacement
        selection = self.view.sel()[0].b
        row, col = self.view.rowcol(selection)

        # replace the content after format
        print("Run Lua Format")
        self.view.replace(edit, r, lua_format(lines, get_settings()))

        # set tab_size from lua-format-setting
        self.view.run_command("set_setting", {"setting": "tab_size", "value": get_settings().get('tab_size', 4)})

        # deal cursor position
        selection = self.view.full_line(self.view.text_point(row - 1, 0)).b
        cursor_pos = sublime.Region(selection, selection)
        regions = self.view.sel()
        regions.clear()
        regions.add(cursor_pos)
        sublime.set_timeout_async(lambda: self.view.show(cursor_pos), 0) 
Example 39
Project: WrapAsYouType   Author: btrekkie   File: wrap_fixer.py    MIT License 5 votes vote down vote up
def _prev_line_region(self, point):
        """Return the Region containing the previous line.

        Return the Region containing the line before the line that
        contains "point", excluding newline characters, if any.

        int point - The point.
        return Region - The previous line region.
        """
        view = self._view
        row = view.rowcol(point)[0]
        if row > 0:
            return view.line(view.text_point(row - 1, 0))
        else:
            return None 
Example 40
Project: WrapAsYouType   Author: btrekkie   File: wrap_fixer.py    MIT License 5 votes vote down vote up
def _next_line_region(self, point):
        """Return the Region containing the next line.

        Return the Region containing the line after the line that
        contains "point", excluding newline characters, if any.

        int point - The point.
        return Region - The next line region.
        """
        view = self._view
        line_region = view.full_line(point)
        if line_region.end() < view.size():
            return view.line(line_region.end())
        else:
            return None 
Example 41
Project: WrapAsYouType   Author: btrekkie   File: wrap_fixer.py    MIT License 5 votes vote down vote up
def _erase_preceding_line_break_edit(self, point):
        """Return a pair with an edit for erasing the preceding line break.

        Return a pair whose first element is an edit for erasing all of
        the text from the most recent line break character up to the
        selection cursor.  This also erases any trailing whitespace on
        the line before the line break.  The second element of the
        return value is the recommended new point - the position to
        which "point" is moved after the erasure.  Clients ought to
        check that _should_erase_preceding_line_break returns True
        before calling this method.  See the comments for
        _should_erase_preceding_line_break for more information
        concerning the motivation of such an edit.

        int point - The position.
        return tuple<tuple<Region, str>, int> - A pair consisting of the
            edit and the new position, respectively.
        """
        # Compute the region to erase
        view = self._view
        line_region = view.line(point)
        line = view.substr(line_region)
        prev_line_region = self._prev_line_region(point)
        prev_line = view.substr(prev_line_region)
        erase_start_point = self._end_point_excluding_whitespace(
            prev_line, prev_line_region)
        erase_end_point = (
            line_region.begin() + len(self._leading_whitespace(line)))
        erase_region = Region(erase_start_point, erase_end_point)

        # Return the edit and the new position
        edit = (erase_region, '')
        if point <= erase_region.begin():
            return (edit, point)
        elif point <= erase_region.end():
            return (edit, erase_region.begin())
        else:
            return (edit, point - erase_region.size()) 
Example 42
Project: WrapAsYouType   Author: btrekkie   File: wrap_fixer.py    MIT License 5 votes vote down vote up
def _try_backwards_join_edit(self, section, point, line_start):
        """Return a pair containing the edit for joining backwards, if any.

        Return a pair whose first element is the edit for joining the
        line containing "point" with the previous line, if we should do
        so.  If adding the first word on the current line to the
        previous line results in a line that is no longer than the wrap
        width, then we join the text on the two lines, assuming they are
        in the same paragraph and section.  This would be followed up
        with a split operation (as in _try_split_edit) if necessary to
        ensure that the current line is no longer than the wrap width.
        The second element of the return value is the recommended new
        point - the position of the former end of the previous line.
        This method returns (None, None) if we should not perform a join
        operation.

        dict<str, object> section - The current section, formatted like
            the elements of _settings_parser.sections.
        int point - The current position.
        str line_start - The line start.
        return tuple<tuple<Region, str>, int> - A pair consisting of the
            edit and the new position, respectively.
        """
        prev_line_region = self._prev_line_region(point)
        if prev_line_region is not None:
            return self._try_join_edit(
                section, prev_line_region.end(), line_start)
        else:
            return (None, None) 
Example 43
Project: WrapAsYouType   Author: btrekkie   File: wrap_fixer.py    MIT License 5 votes vote down vote up
def on_modified(self):
        """Respond to a modification to the WrapFixer's View's content.

        This method is called before performing any resulting word wrap
        fixup.  It is also called for the modifications that comprise
        the actual word wrap fixup.
        """
        self._edits_gen = None
        self._first_edit = None

        # If the user pressed the enter key (or performed an analogous
        # operation), mark the last line break as an explicit line break.  We
        # preserve this line break, by treating the two lines adjacent to it as
        # belonging to separate paragraphs.  The idea is that by pressing the
        # enter key, the user has expressed a desire that the document contain
        # the resulting line break.  For performance reasons, there is at most
        # one explicit line break at any given moment.
        if not self._settings_parser.is_disabled:
            self._prev_selection_point = self._selection_point()
            command_name, command_args, _ = self._view.command_history(0)
            if (self._prev_selection_point is not None and
                    self._has_explicit_line_break(
                        command_name, command_args) and
                    not self._view.command_history(1)[0]):
                line_region = self._view.line(self._prev_selection_point)
                if line_region.begin() > 0:
                    line_break_region = Region(
                        line_region.begin() - 1, line_region.begin())
                    self._view.add_regions(
                        'wrap_as_you_type_explicit_line_break',
                        [line_break_region], '') 
Example 44
Project: StataImproved   Author: zizhongyan   File: StataImproved.py    MIT License 5 votes vote down vote up
def run(self, edit):
		getme = list(map(lambda x: x.begin(), self.view.find_all('piu_sign'))) 
		selss = self.view.sel()
		for sel in selss:
			def findme(q_type, quotes):
				length, tos, froms = False, False, False
				if len(quotes) - self.view.substr(sel).count('piu_sign') >= 2:
					starts = list(filter(lambda x: x < sel.begin(), quotes))
					ends = list(filter(lambda x: x >= sel.end(), quotes)) 
					if starts: tos = starts[-1]
					if ends: froms = ends[0]
					if starts and ends: length = froms - tos
				return length, tos, froms 
			touse1, touse2, touse3 = findme('Piu_Sign', getme)  
			def replace_region(start, end):
				if sel.size() < end-start-2:
					start += 1; end -= 1
				self.view.sel().subtract(sel)
				self.view.sel().add(sublime.Region(start-64, end+15))
			replace_region(touse2, touse3+1) 
		selectedcode = ""
		if len(getme)==0:  
			selectedcode = self.view.substr(sublime.Region(0, self.view.size()))
		if len(getme)!=0: 
			sels = self.view.sel()
			for sel in sels:
				selectedcode = selectedcode + self.view.substr(sel) 
		selectedcode = selectedcode + "\n"   
		dofile_path = os.path.join(os.path.dirname(self.view.file_name()), 'from_sublime.do')
		dofile_path =tempfile.gettempdir()+'BLOCK_piupiu.do'
		with codecs.open(dofile_path, 'w', encoding='utf-8') as out:  
		    out.write(selectedcode) 
		version, stata_app_id = get_stata_version()
		cmd = """osascript<< END
		 tell application id "{0}" 
		    DoCommandAsync "do {1}"  with addToReview
		 end tell 
		 END""".format(stata_app_id,dofile_path,"Viewer") 
		os.system(cmd) 
Example 45
Project: SublimeConfluence   Author: mlf4aiur   File: Confluence.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def post(self):
        region = sublime.Region(0, self.view.size())
        contents = self.view.substr(region)
        markup = Markup()
        meta, content = markup.get_meta_and_content(contents)
        syntax = self.view.settings().get("syntax")
        new_content = markup.to_html("\n".join(content), syntax)
        if not new_content:
            return
        self.confluence_api = ConfluenceApi(self.username, self.password, self.base_uri)
        response = self.confluence_api.get_content_by_title(
            meta["space_key"], meta["ancestor_title"])
        if response.ok:
            ancestor = response.json()["results"][0]
            ancestor_id = int(ancestor["id"])
            space = dict(key=meta["space_key"])
            body = dict(storage=dict(value=new_content, representation="storage"))
            data = dict(type="page", title=meta["title"], ancestors=[dict(id=ancestor_id)],
                        space=space, body=body)
            result = self.confluence_api.create_content(data)
            if result.ok:
                self.view.settings().set("confluence_content", result.json())
                # copy content url
                content_uri = self.confluence_api.get_content_uri(result.json())
                sublime.set_clipboard(content_uri)
                sublime.status_message(self.MSG_SUCCESS)
            else:
                print(result.text)
                sublime.error_message("Can not create content, reason: {}".format(result.reason))
        else:
            print(response.text)
            sublime.error_message("Can not get ancestor, reason: {}".format(response.reason)) 
Example 46
Project: arcadia-repl   Author: selfsame   File: nrepl.py    MIT License 5 votes vote down vote up
def entered_text(view): return view.substr(sublime.Region(G["prompt"], view.size())) 
Example 47
Project: arcadia-repl   Author: selfsame   File: nrepl.py    MIT License 5 votes vote down vote up
def place_cursor_at_end(view):
    view.sel().clear()
    end_region = sublime.Region(view.size(),view.size())
    view.sel().add(end_region)
    G["prompt"] = view.size()
    view.show(end_region) 
Example 48
Project: arcadia-repl   Author: selfsame   File: nrepl.py    MIT License 5 votes vote down vote up
def run(self, edit):
        if not G["active"]: pass
        repl = get_repl(self.view.window())
        repl.replace(edit,sublime.Region(0, repl.size()), G["namespace"])
        place_cursor_at_end(repl) 
Example 49
Project: arcadia-repl   Author: selfsame   File: nrepl.py    MIT License 5 votes vote down vote up
def run(self, edit, i=0):
        if not G["active"]: pass
        repl = get_repl(self.view.window())
        if (len(history) * -1) <= G["hist"] + i < 0:
            G["hist"] += i
            repl.replace(edit,sublime.Region(G["prompt"], repl.size()), history[G["hist"]]) 
Example 50
Project: arcadia-repl   Author: selfsame   File: arcadia_repl.py    MIT License 5 votes vote down vote up
def entered_text(view): return view.substr(sublime.Region(G["prompt"], view.size())) 
Example 51
Project: arcadia-repl   Author: selfsame   File: arcadia_repl.py    MIT License 5 votes vote down vote up
def place_cursor_at_end(view):
    view.sel().clear()
    end_region = sublime.Region(view.size(),view.size())
    view.sel().add(end_region)
    G["prompt"] = view.size()
    view.show(end_region) 
Example 52
Project: arcadia-repl   Author: selfsame   File: arcadia_repl.py    MIT License 5 votes vote down vote up
def run(self, edit):
        if not G["active"]: pass
        repl = get_repl(self.view.window())
        repl.replace(edit,sublime.Region(0, repl.size()), G["namespace"][1:])
        place_cursor_at_end(repl) 
Example 53
Project: arcadia-repl   Author: selfsame   File: arcadia_repl.py    MIT License 5 votes vote down vote up
def run(self, edit, i=0):
        if not G["active"]: pass
        repl = get_repl(self.view.window())
        if (len(history) * -1) <= G["hist"] + i < 0:
            G["hist"] += i
            repl.replace(edit,sublime.Region(G["prompt"], repl.size()), history[G["hist"]]) 
Example 54
Project: sublime-text-keybinding-helper   Author: r-stein   File: command_assistant.py    MIT License 5 votes vote down vote up
def _reset_sel(view):
    view.sel().clear()
    view.sel().add(sublime.Region(0, 0)) 
Example 55
Project: sublime-text-keybinding-helper   Author: r-stein   File: command_assistant.py    MIT License 5 votes vote down vote up
def run(self, edit, info):
        view = self.view
        content_length = view.settings().get("kh_content_length", view.size())
        content_region = sublime.Region(content_length, view.size())
        view.replace(edit, content_region, info) 
Example 56
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def run(self, edit):
        self.edit = edit
        # First, read everything in this view
        reverything = sublime.Region(0, self.view.size())
        self.body = list(self.view.substr(reverything))

        self.view.erase(edit, reverything)

        sublime.set_timeout(self.nextchar, 2000) 
Example 57
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def update_regions(self, length):
		region = self.region
		end = self.region.end()
		for command in cdb_commands:
			if command.region.begin() >= end or command.region.intersects(region):
				command.region = sublime.Region(command.region.a + length, command.region.b + length)
		self.update_status() 
Example 58
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def sendtocdb(self, edit):
		global cdb_process
		global cdb_shutting_down

		sels = self.view.sel()
		end_sel = 0
		# Support multiple selections
		for sel in sels:
			# Get all the lines in the selection
			lines = self.view.lines(sel)

			end = sel.end()
			if end_sel < end:
				end_sel = end

			# Check each line
			for line in lines:
				line_content = self.view.substr(line)

				if line_content.startswith(">"):
					line_content = line_content[1:]
				elif cdb_command.search(line_content):
					pos = line_content.index(">") + 1
					line_content = line_content[pos:]
				else:
					line_content = ""

				if line_content != "":
					self.pend(edit, line, line_content)
		sels.clear()
		sels.add(sublime.Region(end_sel, end_sel)) 
Example 59
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def scroll(self, view, fpath, r=1, c=1, text=None, region=None):
        if sublime.active_window() != self.window:
                print("changed active_window")
                return
        if self.window.active_view() != view:
                print("changed active_view")
                return
        if view.is_loading() or view.file_name() != fpath:
                print("retry scroll")
                sublime.set_timeout(
                    lambda: self.scroll(view, fpath, r, c, text, region), 300)
                return
        if not region:
            point = view.text_point(r-1, c-1)
            if text:
                line = view.line(point)
                region = view.find(text, line.begin(), sublime.LITERAL)
            elif r > 1:
                region = Region(point, point)
        if region:
            if region.a == region.b and text:
                region = view.find(text, region.a-1, sublime.LITERAL)
            view.show_at_center(region)
            view.sel().clear()
            view.sel().add(region)
            if not view.visible_region().contains(region):
                sublime.set_timeout(
                    lambda: self.scroll(view, fpath, r, c, text, region), 300)
        self.window.focus_view(view) 
Example 60
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def find_in_scope(self, text, row):
        win = self.window
        view = win.active_view()
        rows = self.get_scoped_rowdict(row)

        results = view.find_all('\\b'+text+'\\b')
        result_up = []
        result_down = []
        for region in results:
            r, c = view.rowcol(region.begin())
            r, c = r+1, c+1
            if r >= row and len(result_up) > 0:
                break
            if r in rows:
                lv = rows[r][0]
                line = view.line(region.begin())
                before = view.substr(Region(line.begin(), region.begin()))
                # after = view.substr(Region(region.end(), line.end()))
                if re.search(r'[=\)\[\]\{\}]', before):
                    # maybe expr
                    continue
                if r < row:
                    result_up.append((-lv, r, c, region))
                elif r > row:
                    result_down.append((region, r, c))

        if len(result_up) > 0:
            result_up.sort()
            result_up = [(a[3], a[1], a[2]) for a in result_up]
            return result_up[0]
        if len(result_down):
            return result_down[0]
        return None 
Example 61
Project: RainbowBrackets   Author: absop   File: main.py    MIT License 4 votes vote down vote up
def search_nearest_brackets(self, region):
        def search(region, opening, closing, next):
            stack = []
            while full_text_region.contains(region):
                tokens = view.extract_tokens_with_scopes(region)
                if tokens:
                    region, scope = tokens[0]
                    if not match_selector(region.a, selector):
                        token = substr(region)
                        if token in opening:
                            if stack:
                                if pairs[stack[-1]] == token:
                                    stack.pop()
                                else:
                                    return False
                            else:
                                if pair[0] is None:
                                    pair[0] = (region, token)
                                    return True
                                elif pair[0][1] == pairs[token]:
                                    pair[1] = (region, token)
                                    return True
                        elif token in closing:
                            stack.append(token)
                    next(region)
                else:
                    return False
            return False

        def last(region):
            region.a = region.b = region.begin() - 1

        def next(region):
            region.a = region.end()
            region.b = region.a + 1

        view, pair = self.view, [None, None]
        full_text_region = sublime.Region(0, view.size())
        values = RainbowBracketsViewListener.get_brackets(view)
        o = values["opening"]
        c = values["closing"]
        pairs = values["pairs"]
        selector = values["selector"]

        self.bracket_pairs = pairs

        substr = view.substr
        match_selector = view.match_selector
        begin, end = region.begin(), region.end()
        left = sublime.Region(begin - 1, begin)
        right = sublime.Region(end, end + 1)
        search(left, o, c, last) and search(right, c, o, next)

        return pair[0] and pair[1] and (pair[0][0], pair[1][0]) 
Example 62
Project: RainbowBrackets   Author: absop   File: main.py    MIT License 4 votes vote down vote up
def find_all_bracket_regions(self):
        view, selector = self.view, self.selector
        opening, pairs = self.opening, self.pairs
        full_text = view.substr(sublime.Region(0, view.size()))

        number_levels = self.color_number
        matched_regions = [list() for i in range(number_levels)]
        bracket_stack, region_stack = [], []

        if selector:
            for region in view.find_all(self.pattern):
                if view.match_selector(region.a, selector):
                    continue

                bracket = full_text[region.a:region.b]

                if bracket in opening:
                    region_stack.append(region)
                    bracket_stack.append(bracket)

                elif bracket_stack and bracket == pairs[bracket_stack[-1]]:
                    bracket_stack.pop()
                    level = len(bracket_stack) % number_levels
                    matched_regions[level].append(region_stack.pop())
                    matched_regions[level].append(region)

                else:
                    self.mismatched_regions.append(region)
        else:
            for region in view.find_all(self.pattern):
                bracket = full_text[region.a:region.b]

                if bracket in opening:
                    region_stack.append(region)
                    bracket_stack.append(bracket)

                elif bracket_stack and bracket == pairs[bracket_stack[-1]]:
                    bracket_stack.pop()
                    level = len(bracket_stack) % number_levels
                    matched_regions[level].append(region_stack.pop())
                    matched_regions[level].append(region)

                else:
                    self.mismatched_regions.append(region)

        self.matched_regions = [ls for ls in matched_regions if ls] 
Example 63
Project: dired   Author: kublaios   File: dired.py    MIT License 4 votes vote down vote up
def run(self, edit, goto=None):
        """
        goto
            Optional filename to put the cursor on.
        """
        path = self.path

        names = os.listdir(path)
        names.sort()
        f = []
        for name in names:
            if self.is_omitted(name):
                continue
            if isdir(join(path, name)):
                name += os.sep
            f.append(name)

        marked = set(self.get_marked())

        text = [ path ]
        text.append('')
        text.extend(f)
        text.append('')
        text.append(NORMAL_HELP)

        self.view.set_read_only(False)

        self.view.erase(edit, Region(0, self.view.size()))
        self.view.insert(edit, 0, '\n'.join(text))
        self.view.set_syntax_file('Packages/dired/dired.tmLanguage')
        self.view.settings().set('dired_count', len(f))

        if marked:
            # Even if we have the same filenames, they may have moved so we have to manually
            # find them again.
            regions = []
            for line in self.view.lines(self.fileregion()):
                filename = RE_FILE.match(self.view.substr(line)).group(1)
                if filename in marked:
                    regions.append(line)
            self.view.add_regions('marked', regions, 'dired.marked', 'dot', 0)
        else:
            self.view.erase_regions('marked')

        self.view.set_read_only(True)

        # Place the cursor.
        if f:
            pt = self.fileregion().a
            if goto:
                if isdir(join(path, goto)) and not goto.endswith(os.sep):
                    goto += os.sep
                try:
                    line = f.index(goto) + 2
                    pt = self.view.text_point(line, 0)
                except ValueError:
                    pass

            self.view.sel().clear()
            self.view.sel().add(Region(pt, pt)) 
Example 64
Project: dired   Author: kublaios   File: common.py    MIT License 4 votes vote down vote up
def _mark(self, mark=None, regions=None):
        """
        Marks the requested files.

        mark
            True, False, or a function with signature `func(oldmark, filename)`.  The function
            should return True or False.

        regions
            Either a single region or a sequence of regions.  Only files within the region will
            be modified.
        """
        # Allow the user to pass a single region or a collection (like view.sel()).
        if isinstance(regions, Region):
            regions = [ regions ]

        filergn = self.fileregion()

        # We can't update regions for a key, only replace, so we need to record the existing
        # marks.
        previous = self.view.get_regions('marked')
        marked = { RE_FILE.match(self.view.substr(r)).group(1): r for r in previous }

        for region in regions:
            for line in self.view.lines(region):
                if filergn.contains(line):
                    text = self.view.substr(line)
                    filename = RE_FILE.match(text).group(1)

                    if mark not in (True, False):
                        newmark = mark(filename in marked, filename)
                        assert newmark in (True, False), 'Invalid mark: {}'.format(newmark)
                    else:
                        newmark = mark

                    if newmark:
                        marked[filename] = line
                    else:
                        marked.pop(filename, None)

        if marked:
            r = sorted(list(marked.values()), key=lambda region: region.a)
            self.view.add_regions('marked', r, 'dired.marked', 'dot', 0)
        else:
            self.view.erase_regions('marked') 
Example 65
Project: sublime-Jenkinsfile   Author: june07   File: Jenkinsfile.py    MIT License 4 votes vote down vote up
def run(self, edit):
    view = self.view
    if os.path.basename(view.file_name()) == 'Jenkinsfile':      
      view = self.view
      view.erase_phantoms('alerts')
      jenkinsfileRegion = sublime.Region(0, view.size())
      jenkinsfileString = view.substr(jenkinsfileRegion)
      logger.debug(jenkinsfileString)
      process = Popen(['plink', '-v', '-load', settings.get('pageant_session'), 'declarative-linter'], stdout=PIPE, stdin=PIPE, stderr=PIPE, startupinfo=startupinfo)
      process_output = process.communicate(input=bytes(jenkinsfileString, 'UTF-8'))
      stdout_data = (process_output[0]).decode('UTF-8')
      stderr_data = (process_output[1]).decode('UTF-8')
      
      if stderr_data:
        logger.debug('ERROR ' + stderr_data)
      logger.debug(stdout_data)

      errors = None
      output = stdout_data.splitlines()
      if output[0].lower().find('jenkinsfile successfully validated') != -1:
        sublime.set_timeout_async(lambda: status_message(output[0]), 1000)
        logger.debug(output[0])
        return
      else:
        errors = output

      phantom = None
      for e in errors:
        matches = re.finditer('line (([0-9]{1,}),)', e)
        for matchNum, match in enumerate(matches, start=1):
          #print('MATCH FOUND ' + match.group(2))
          region = view.line(view.text_point(int(match.group(2))-1, 0))
          view.add_phantom(region=region, content='''
            <html>
              <body id="jenkinsfile">
                  <style>
                    .dot {
                      height: 8px;
                      width: 8px;
                      background-color: red;
                      border-radius: 50%;
                      display: block;
                    }
                  </style>
                  <div class="error">
                    <code>''' +
                    stdout_data + '''</code>
                  </div>
              </body>
            </html>''',
          layout=sublime.LAYOUT_BELOW,
          key='alerts')
          sublime_plugin.on_hover(view.id(), 0, sublime.HOVER_GUTTER) 
Example 66
Project: cs-script-sublime   Author: oleg-shilo   File: cs-script.py    MIT License 4 votes vote down vote up
def run(self, edit):
        mark_as_formatted(self.view)
        sublime.status_message('Formatting script "'+self.view.file_name()+'"')

        # position in text and in file mey not be the same depending on line endings type
        text_location = -1
        if len(self.view.sel()) > 0:
            text_location = self.view.sel()[0].begin()

        (curr_doc, file_location, as_temp_file) = get_saved_doc(self.view)

        response = send_formatting_request(curr_doc, file_location)

        if as_temp_file:
            os.remove(curr_doc)

        if response.startswith('<error>'):
            print('Formatting error:', response.replace('<error>', ''))
        else:
            parts = response.split('\n', 1)

            new_file_location = int(parts[0])
            formatted_code = parts[1]

            new_text_location = to_text_pos(formatted_code, new_file_location)
            new_text = formatted_code.replace('\r', '')

            self.view.replace(edit, sublime.Region(0, self.view.size()), new_text)
            # with open(self.view.file_name(), "w") as file:
            #     file.write(formatted_code)

            # surprisingly mapping of selection is not required. ST3 does it by itself
            # self.view.sel().clear()
            # self.view.sel().add(sublime.Region(new_text_location, new_text_location))

            # print('formatting done')
            # sublime.active_window().run_command("save")


# =================================================================================
# CS-Script async replecement service
# =================================================================================
# DONE 
Example 67
Project: cs-script-sublime   Author: oleg-shilo   File: cs-script.py    MIT License 4 votes vote down vote up
def do(self):
        try:
            csscript_resolve_using.inprogress = True

            view = self.view

            word_region = view.word(self.point)
            word_to_resolve = view.substr(word_region)
            # print('view', view.file_name())

            (saved_doc, location, as_temp_file) = get_saved_doc(view)

            response = send_resolve_using_request(saved_doc, word_to_resolve)
            busy_indicator.hide()

            if as_temp_file:
                os.remove(saved_doc)

            if response == '<null>':
                pass
            elif response.startswith('<error>'):
                print(response.replace('<error>', 'CS-Script error: '))
            else:
                items = response.split('\n')
                def on_done(index):
                    if index != -1:
                        for region in self.view.lines(sublime.Region(0,self.view.size())):
                            line  = self.view.substr(region)
                            if not line.startswith("//"):
                                # cannot use 'self.view.replace(self.edit...' as edit is already invalid
                                # so need to start a new command that ctreats 'edit'; Remember, 'edit' cannot be created from code
                                # self.view.replace(self.edit, sublime.Region(start, start), 'using '+items[index]+';'+'\n')
                                region = str(region.begin())+','+str(region.begin())
                                replacement = 'using '+items[index]+';'+'\n'
                                sublime.active_window().run_command("csscript_resolve_using_async", {'replacement':replacement, 'region':region})
                                sublime.active_window().run_command('save')
                                break

                if self.first_suffestion:
                    on_done(0)
                else:
                    self.view.show_popup_menu(items, on_done, 1)

        except Exception as err:
            print(err)

        busy_indicator.hide()
        csscript_resolve_using.inprogress = False

# =================================================================================
# CS-Script tooltip service (for invoking via hotkeys)
# ================================================================================= 
Example 68
Project: cs-script-sublime   Author: oleg-shilo   File: cs-script.py    MIT License 4 votes vote down vote up
def run(self, edit, **args):

        view = self.view

        sublime.status_message('Checking syntax of "'+view.file_name()+'"')

        if view.is_dirty() and not 'skip_saving' in args.keys():
            sublime.active_window().run_command("save")

        curr_doc = view.file_name()

        clear_and_print_result_header(curr_doc)

        if not path.exists(csscriptApp):
            print('Error: cannot find CS-Script launcher - ', csscriptApp)
        elif not curr_doc:
            print('Error: cannot find out the document path')
        else:

            clear_and_print_result_header(curr_doc)
            if '//css_nuget' in view.substr(sublime.Region(0, view.size())):
                output_view_write_line(out_panel, "Resolving NuGet packages may take time...")
            csscript_syntax_check.clear_errors()


            proc = popen_redirect([csscriptApp, "-nl", '-l', "-check", curr_doc])
            first_result = True
            for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"):
                line = line.strip()
                if first_result:
                    first_result = False
                    clear_and_print_result_header(curr_doc)

                output_view_write_line(out_panel, line)
                error_info = extract_location(line.strip())
                if error_info:

                    file, line, column, context = error_info
                    file = os.path.abspath(file)
                    if file not in csscript_syntax_check.errors.keys():
                        csscript_syntax_check.errors[file] = []

                    csscript_syntax_check.errors[file].append((line, column, context))
            output_view_write_line(out_panel, "[Syntax check]")

            csscript_syntax_check.show_errors()

    # ----------------- 
Example 69
Project: cs-script-sublime   Author: oleg-shilo   File: cs-script.py    MIT License 4 votes vote down vote up
def run(self):
        view_name = sublime.active_window().active_panel()
        if not view_name:
            return

        if view_name == 'output.exec':
            self.window.run_command('next_result')
        else:
            if view_name.startswith('output.'):
                view_name = view_name.replace('output.', '')

            view = sublime.active_window().find_output_panel(view_name)

            if not view or not view.window():
                return

            caret_point = view.sel()[0].begin()
            caret_line_region = view.line(caret_point)
            line_regions = view.lines(sublime.Region(0, view.size()))

            next_location_index = -1
            locations = []

            for rg in line_regions:
                line = view.substr(rg).strip()
                info = extract_location(line)
                if info:
                    if next_location_index == -1 and rg == caret_line_region:
                        next_location_index = len(locations)
                    locations.append((rg, line))

            if len(locations) > 0:
                next_location_index = next_location_index + 1

                if next_location_index >= len(locations):
                    next_location_index = 0

                line_region, line_text = locations[next_location_index]

                view.sel().clear()
                view.sel().add(line_region)
                view.run_command('append', {'characters': ''}) # to force repainting the selection

                navigate_to_file_ref(line_text)

# =================================================================================
# CS-Script go-to-definition service
# ================================================================================= 
Example 70
Project: WrapAsYouType   Author: btrekkie   File: test_command_special.py    MIT License 4 votes vote down vote up
def test_beginning_of_document(self):
        """Test word wrapping at the beginning of the document.

        Test word wrapping of a section of line comments that starts at
        the beginning of the document.
        """
        view = self._view
        self._set_up_cpp()
        view.settings().set('rulers', [60])

        comment_start_point = 0
        self._insert(
            comment_start_point,
            '// Lorem ipsum dolor sit amet, iudicabit interpretaris ius eu, '
            'et sit iudico aperiri scaevola. Ad solum eleifend sea, ex ius '
            'graeci alienum accusamus, diam mandamus expetenda quo ei.\n')
        expected_text = (
            '// Lorem ipsum dolor sit amet, iudicabit interpretaris ius\n'
            '// eu, et sit iudico aperiri scaevola. Ad solum eleifend\n'
            '// sea, ex ius graeci alienum accusamus, diam mandamus\n'
            '// expetenda quo ei.\n')
        actual_text = view.substr(Region(0, view.size()))
        self.assertEqual(actual_text, expected_text)

        point = view.find(r'aperiri scaevola\.', 0).end()
        self._insert(
            point,
            ' Vim case eros choro et, te deserunt iudicabit assentior eum, id '
            'his assum nobis primis.')
        expected_text = (
            '// Lorem ipsum dolor sit amet, iudicabit interpretaris ius\n'
            '// eu, et sit iudico aperiri scaevola. Vim case eros choro\n'
            '// et, te deserunt iudicabit assentior eum, id his assum\n'
            '// nobis primis. Ad solum eleifend sea, ex ius graeci\n'
            '// alienum accusamus, diam mandamus expetenda quo ei.\n')
        actual_text = view.substr(Region(0, view.size()))
        self.assertEqual(actual_text, expected_text)

        point = view.find('Lorem ipsum', 0).begin()
        self._delete(point, 92)
        expected_text = (
            '// Vim case eros choro et, te deserunt iudicabit assentior\n'
            '// eum, id his assum nobis primis. Ad solum eleifend sea, ex\n'
            '// ius graeci alienum accusamus, diam mandamus expetenda quo\n'
            '// ei.\n')
        actual_text = view.substr(Region(0, view.size()))
        self.assertEqual(actual_text, expected_text) 
Example 71
Project: WrapAsYouType   Author: btrekkie   File: test_command_special.py    MIT License 4 votes vote down vote up
def test_end_of_document(self):
        """Test word wrapping at the end of the document.

        Test word wrapping of a C++ block comment that isn't closed with
        a */, and so extends to the end of the document.
        """
        view = self._view
        self._set_up_cpp()
        view.settings().set('rulers', [60])

        self._append(
            '#include <iostream>\n'
            '\n'
            'using namespace std;\n'
            '\n')

        comment_start_point = view.size()
        self._insert(
            comment_start_point,
            '/**\n'
            ' * Lorem ipsum dolor sit amet, iudicabit interpretaris ius eu, '
            'et sit iudico aperiri scaevola. Ad solum eleifend sea, ex ius '
            'graeci alienum accusamus, diam mandamus expetenda quo ei.')
        expected_text = (
            '/**\n'
            ' * Lorem ipsum dolor sit amet, iudicabit interpretaris ius\n'
            ' * eu, et sit iudico aperiri scaevola. Ad solum eleifend\n'
            ' * sea, ex ius graeci alienum accusamus, diam mandamus\n'
            ' * expetenda quo ei.')
        actual_text = view.substr(Region(comment_start_point, view.size()))
        self.assertEqual(actual_text, expected_text)

        point = view.find(r'aperiri scaevola\.', 0).end()
        self._insert(
            point,
            ' Vim case eros choro et, te deserunt iudicabit assentior eum, id '
            'his assum nobis primis.')
        expected_text = (
            '/**\n'
            ' * Lorem ipsum dolor sit amet, iudicabit interpretaris ius\n'
            ' * eu, et sit iudico aperiri scaevola. Vim case eros choro\n'
            ' * et, te deserunt iudicabit assentior eum, id his assum\n'
            ' * nobis primis. Ad solum eleifend sea, ex ius graeci\n'
            ' * alienum accusamus, diam mandamus expetenda quo ei.')
        actual_text = view.substr(Region(comment_start_point, view.size()))
        self.assertEqual(actual_text, expected_text)

        point = view.find('Lorem ipsum', 0).begin()
        self._delete(point, 92)
        expected_text = (
            '/**\n'
            ' * Vim case eros choro et, te deserunt iudicabit assentior\n'
            ' * eum, id his assum nobis primis. Ad solum eleifend sea, ex\n'
            ' * ius graeci alienum accusamus, diam mandamus expetenda quo\n'
            ' * ei.')
        actual_text = view.substr(Region(comment_start_point, view.size()))
        self.assertEqual(actual_text, expected_text) 
Example 72
Project: WrapAsYouType   Author: btrekkie   File: test_command_special.py    MIT License 4 votes vote down vote up
def test_wrap_entire_document(self):
        """Test a "wrap_as_you_type_sections" setting that wraps everything.

        Test a "wrap_as_you_type_sections" setting that performs word
        wrapping on the entire document.
        """
        view = self._view
        view.set_syntax_file('Packages/Text/Plain text.tmLanguage')
        settings = view.settings()
        settings.set(
            'wrap_as_you_type_sections', [{'selector': 'source | text'}])
        settings.set('rulers', [60])

        self._insert(
            0,
            'Lorem ipsum dolor sit amet, iudicabit interpretaris ius eu, et '
            'sit iudico aperiri scaevola. Ad solum eleifend sea, ex ius '
            'graeci alienum accusamus, diam mandamus expetenda quo ei.\n')
        expected_text = (
            'Lorem ipsum dolor sit amet, iudicabit interpretaris ius eu,\n'
            'et sit iudico aperiri scaevola. Ad solum eleifend sea, ex\n'
            'ius graeci alienum accusamus, diam mandamus expetenda quo\n'
            'ei.\n')
        actual_text = view.substr(Region(0, view.size()))
        self.assertEqual(actual_text, expected_text)

        point = view.find(r'aperiri scaevola\.', 0).end()
        self._insert(
            point,
            ' Vim case eros choro et, te deserunt iudicabit assentior eum, id '
            'his assum nobis primis.')
        expected_text = (
            'Lorem ipsum dolor sit amet, iudicabit interpretaris ius eu,\n'
            'et sit iudico aperiri scaevola. Vim case eros choro et, te\n'
            'deserunt iudicabit assentior eum, id his assum nobis primis.\n'
            'Ad solum eleifend sea, ex ius graeci alienum accusamus, diam\n'
            'mandamus expetenda quo ei.\n')
        actual_text = view.substr(Region(0, view.size()))
        self.assertEqual(actual_text, expected_text)

        point = view.find('Lorem ipsum', 0).begin()
        self._delete(point, 92)
        expected_text = (
            'Vim case eros choro et, te deserunt iudicabit assentior eum,\n'
            'id his assum nobis primis. Ad solum eleifend sea, ex ius\n'
            'graeci alienum accusamus, diam mandamus expetenda quo ei.\n')
        actual_text = view.substr(Region(0, view.size()))
        self.assertEqual(actual_text, expected_text) 
Example 73
Project: WrapAsYouType   Author: btrekkie   File: wrap_fixer.py    MIT License 4 votes vote down vote up
def _try_remove_indent_of_next_line_edit(self, section, point, line_start):
        r"""Return an edit for removing subsequent indentation, if appropriate.

        Return an edit for removing the text from "point" up to what
        appears to be the end of the former i_line_start_i of the next
        line, or None if we should not remove such text.

        The goal here is to help the user when he presses the "delete"
        key at the end of a line.  For example, if the line start is
        " * ", the current line of text reads, "   * Foo bar   * baz",
        and the selection cursor is immediately after the word "bar",
        then it looks as though the document used to read,
        "   * Foo bar\n   * baz", and the user just deleted the newline
        character.  In this case, we erase text so that the line reads,
        "   * Foo barbaz" instead.  The purpose of the erasure is to
        make it feel more like editing non-wrapped text content to the
        user (or rather, like editing soft-wrapped content that doesn't
        have any indentation or line start).

        dict<str, object> section - The current section, formatted like
            the elements of _settings_parser.sections.
        int point - The position.
        str line_start - The line start.
        return tuple<Region, str> - The edit, if any.
        """
        line_region = self._view.line(point)
        line = self._view.substr(line_region)
        first_line = line[:point - line_region.begin()]
        second_line = line[point - line_region.begin():]
        i_line_start_i = self._i_line_start_i(second_line, line_start)
        if (i_line_start_i is None or
                self._leading_whitespace(i_line_start_i) in ('', ' ', '  ')):
            # i_line_start_i is too generic for us to confidently guess that
            # the user deleted a newline character
            return None

        # Check _point_matches_selector
        if not self._point_matches_selector(section, point, line_region):
            return None

        # Check whether the "lines" are in the same paragraph
        if (self._same_paragraph_line(
                section, point, first_line, second_line,
                Region(line_region.begin(), point),
                Region(point, line_region.end()), line_start) is None):
            return None

        # Return the edit
        erase_region = Region(point, point + len(i_line_start_i))
        return (erase_region, '') 
Example 74
Project: WrapAsYouType   Author: btrekkie   File: wrap_fixer.py    MIT License 4 votes vote down vote up
def extend_section(self, edit):
        """Insert a newline and the current section's line start.

        If the beginning of the selection cursor is in a wrappable
        section that extends to the beginning of the line, insert a
        newline and the section's line start string, along with the
        appropriate indentation. Otherwise, just insert a newline
        followed by the appropriate indentation.

        sublime.Edit edit - The Edit object to use for the edit.
        """
        view = self._view
        selection = self._view.sel()
        if len(selection) != 1:
            view.run_command('insert', {'characters': '\n'})
            return
        point = selection[0].begin()
        section, line_start = self._section_to_extend(point)
        if section is None:
            view.run_command('insert', {'characters': '\n'})
            return None

        line_region = view.line(point)
        line = view.substr(line_region)
        i_line_start_i = self._i_line_start_i(line, line_start)
        settings = view.settings()
        if settings.get('auto_indent', False):
            length = min(len(i_line_start_i), point - line_region.begin())
            insert_str = '\n{0:s}'.format(i_line_start_i[:length])
        else:
            insert_str = '\n{0:s}{1:s}'.format(
                self._section_indent(line, line_start), line_start)
        if selection[0].empty():
            view.insert(edit, point, insert_str)
        else:
            view.replace(edit, selection[0], insert_str)
            selection.clear()
            selection.add(Region(point + len(insert_str)))

        # This isn't exactly the same behavior as "trim_automatic_white_space",
        # but it's a reasonable approximation
        if (settings.get('trim_automatic_white_space', False) and
                line_region.begin() + len(i_line_start_i) == point):
            match = WrapFixer._TRAILING_WHITESPACE_REGEX.search(i_line_start_i)
            if match.start() < match.end():
                view.erase(
                    edit, Region(line_region.begin() + match.start(), point)) 
Example 75
Project: SublimeConfluence   Author: mlf4aiur   File: Confluence.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def update_from_editor(self):
        # Example Data:
        """
        {
          "id": "3604482",
          "type": "page",
          "title": "new page",
          "space": {
            "key": "TST"
          },
          "body": {
            "storage": {
              "value": "<p>This is the updated text for the new page</p>",
              "representation": "storage"
            }
          },
          "version": {
            "number": 2
          }
        }
        """
        content_id = self.content["id"]
        title = self.content["title"]
        space_key = self.content["space"]["key"]
        version_number = self.content["version"]["number"] + 1
        region = sublime.Region(0, self.view.size())
        contents = self.view.substr(region)
        syntax = self.view.settings().get("syntax")
        if "HTML" in syntax:
            new_content = "".join(contents.split("\n"))
        else:
            markup = Markup()
            meta, content = markup.get_meta_and_content(contents)
            new_content = markup.to_html("\n".join(content), syntax)

        space = dict(key=space_key)
        version = dict(number=version_number, minorEdit=False)
        body = dict(storage=dict(value=new_content, representation="storage"))
        data = dict(id=content_id, type="page", title=title,
                    space=space, version=version, body=body)
        try:
            self.confluence_api = ConfluenceApi(self.username, self.password, self.base_uri)
            response = self.confluence_api.update_content(content_id, data)
            if response.ok:
                content_uri = self.confluence_api.get_content_uri(self.content)
                sublime.set_clipboard(content_uri)
                sublime.status_message(self.MSG_SUCCESS)
                self.view.settings().set("confluence_content", response.json())
            else:
                print(response.text)
                sublime.error_message("Can't update content, reason: {}".format(response.reason))
        except Exception:
            print(response.text)
            sublime.error_message("Can't update content, reason: {}".format(response.reason)) 
Example 76
Project: SublimeConfluence   Author: mlf4aiur   File: Confluence.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def update_from_source(self):
        region = sublime.Region(0, self.view.size())
        contents = self.view.substr(region)
        markup = Markup()
        meta, content = markup.get_meta_and_content(contents)
        syntax = self.view.settings().get("syntax")
        new_content = markup.to_html("\n".join(content), syntax)
        if not new_content:
            sublime.error_message(
                "Can't update: this doesn't appear to be a valid Confluence page.")
            return
        self.confluence_api = ConfluenceApi(self.username, self.password, self.base_uri)

        get_content_by_title_resp = self.confluence_api.get_content_by_title(
            meta["space_key"], meta["title"])
        if get_content_by_title_resp.ok:
            content_id = get_content_by_title_resp.json()["results"][0]["id"]

            get_content_by_id_resp = self.confluence_api.get_content_by_id(content_id)
            if get_content_by_id_resp.ok:
                content = get_content_by_id_resp.json()
                space = dict(key=meta["space_key"])
                version_number = content["version"]["number"] + 1
                version = dict(number=version_number, minorEdit=False)
                # ancestor_id = int(ancestor["id"])
                body = dict(storage=dict(value=new_content, representation="storage"))
                data = dict(id=content_id, type="page", title=meta["title"],
                            space=space, version=version, body=body)

                update_content_resp = self.confluence_api.update_content(content_id, data)
                if update_content_resp.ok:
                    self.view.settings().set("confluence_content", update_content_resp.json())
                    content_uri = self.confluence_api.get_content_uri(update_content_resp.json())
                    sublime.set_clipboard(content_uri)
                    sublime.status_message(self.MSG_SUCCESS)
                else:
                    print(update_content_resp.text)
                    sublime.error_message("Can not update content, reason: {}".format(
                        update_content_resp.reason))
            else:
                print(get_content_by_id_resp.text)
                sublime.error_message("Can not get content by id, reason: {}".format(
                    get_content_by_id_resp.reason))
        else:
            print(get_content_by_title_resp.text)
            sublime.error_message("Can not get content by title, reason: {}".format(
                get_content_by_title_resp.reason)) 
Example 77
Project: arcadia-repl   Author: selfsame   File: nrepl.py    MIT License 4 votes vote down vote up
def run(self, edit, scope="block"):
        if not G["active"]: pass
        repl = get_repl(self.view.window())
        regions, sel = [],[]
        for region in self.view.sel(): sel.append(region)
        if scope == "file":
            send_repl("(do " + self.view.substr(sublime.Region(0, self.view.size())) + ")", False)
            return True
        if scope == "selection":
            for s in sel:
                send_repl(format_transfered_text(self.view, self.view.substr(s)), False)
            return True
        if scope == "block": 
            if transfer_naked(self.view): return True
        if scope == "top-form": 
            if transfer_naked(self.view): return True
            #expand until no change, also make sure sel end is not going backwards
            la = self.view.sel()[0].a
            lb = self.view.sel()[0].b
            for i in range(40):
                self.view.run_command("expand_selection", {"to": "brackets"})
                if (self.view.sel()[0].b < lb):
                    self.view.sel().clear()
                    self.view.sel().add(sublime.Region(la, lb))
                    break
                if (self.view.sel()[0].a == la) & (self.view.sel()[0].b == lb):
                    break
                la = self.view.sel()[0].a
                lb = self.view.sel()[0].b
                
            send_repl(format_transfered_text(self.view, self.view.substr(self.view.sel()[0])), False)
            self.view.sel().clear()
            for region in sel: self.view.sel().add(region)
            return True
        for idx in range(len(self.view.sel())):
            if scope == "block":
                regions.append(sublime.Region(self.view.sel()[idx].a - 1, self.view.sel()[idx].b + 1))
        for pair in regions: 
            for text in find_blocks(self.view, pair.a, pair.b):
                send_repl(format_transfered_text(self.view, text), False)
        self.view.sel().clear()
        for region in sel: self.view.sel().add(region) 
Example 78
Project: arcadia-repl   Author: selfsame   File: arcadia_repl.py    MIT License 4 votes vote down vote up
def run(self, edit, scope="block"):
        if not G["active"]: pass
        repl = get_repl(self.view.window())
        regions, sel = [],[]
        for region in self.view.sel(): sel.append(region)
        if scope == "file":
            send_repl("(do " + self.view.substr(sublime.Region(0, self.view.size())) + ")", False)
            return True
        if scope == "selection":
            for s in sel:
                send_repl(format_transfered_text(self.view, self.view.substr(s)), False)
            return True
        if scope == "block": 
            if transfer_naked(self.view): return True
        if scope == "top-form": 
            if transfer_naked(self.view): return True
            #expand until no change, also make sure sel end is not going backwards
            la = self.view.sel()[0].a
            lb = self.view.sel()[0].b
            for i in range(40):
                self.view.run_command("expand_selection", {"to": "brackets"})
                if (self.view.sel()[0].b < lb):
                    self.view.sel().clear()
                    self.view.sel().add(sublime.Region(la, lb))
                    break
                if (self.view.sel()[0].a == la) & (self.view.sel()[0].b == lb):
                    break
                la = self.view.sel()[0].a
                lb = self.view.sel()[0].b
                
            send_repl(format_transfered_text(self.view, self.view.substr(self.view.sel()[0])), False)
            self.view.sel().clear()
            for region in sel: self.view.sel().add(region)
            return True
        for idx in range(len(self.view.sel())):
            if scope == "block":
                regions.append(sublime.Region(self.view.sel()[idx].a - 1, self.view.sel()[idx].b + 1))
        for pair in regions: 
            for text in find_blocks(self.view, pair.a, pair.b):
                send_repl(format_transfered_text(self.view, text), False)
        self.view.sel().clear()
        for region in sel: self.view.sel().add(region) 
Example 79
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 4 votes vote down vote up
def get_scoped_rowdict(self, row):
        win = self.window
        view = win.active_view()

        rows = {}
        text = view.substr(Region(0, view.size()))
        lines = text.split("\n")

        cur = 0
        indents = []
        for ln in lines:
            if self.is_comment(ln):
                indents.append(False)
                continue
            m = re.search(r'^[ \t]*', ln)
            i = len(m.group(0))
            if i == len(ln):
                indents.append((cur, ln))
            else:
                indents.append((i, ln))
                cur = i

        if not indents[row-1]:
            return {}

        cur = indents[row-1][0]
        for r in range(row, 0, -1):
            if not indents[r-1]:
                continue
            i = indents[r-1][0]
            if i == cur:
                rows[r] = (i*10, indents[r-1][1])
            elif i < cur:
                # up scope
                rows[r] = (i*10+5, indents[r-1][1])
                # add same scope lines after row
                for rr in range(row+1, len(indents)+1):
                    if not indents[rr-1]:
                        continue
                    j = indents[rr-1][0]
                    if j < i:
                        break
                    elif j == i:
                        rows[rr] = (j*10, indents[rr-1][1])
                cur = i
        return rows 
Example 80
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 4 votes vote down vote up
def get_undercursor(self):
        view = self.view
        sel = view.sel()[0]
        pos = sel.begin()
        line = view.line(pos)
        before = view.substr(Region(line.begin(), pos))
        after = view.substr(Region(pos, line.end()))
        is_symbol = False

        for sep1, sep2 in [('"', '"'), ("'", "'"), ("<", ">"), ]:
            if before.find(sep1) == -1 or after.find(sep2) == -1:
                continue
            b = before.split(sep1)
            a = after.split(sep2)
            if len(b) > 1 and len(b) % 2 == 0:
                text = b[-1] + a[0]
                text, is_symbol = self.mod_bracket_text(text, sep1, b, a)
                text = re.sub(r'\{.*\}', '', text)
                if text.find('./') > -1:
                    text = os.path.normpath(text)
                return text, is_symbol

        b = re.split(r'[\s\n\r]', before)
        a = re.split(r'[\s\n\r]', after)
        text = b[-1] + a[0]

        text, is_symbol = self.mod_space_sep_text(text, b, a)

        if text.find('/') > -1:
            test = re.split(r'[\[\]\(\)\{\}\!\#\,\<\>]', text)
            if len(test) == 1:
                return text, is_symbol

        is_symbol = True

        # word = view.word(pos)
        # text = view.substr(word).strip()
        b = re.search(r'[a-zA-Z0-9_$\-]*$', before).group(0)  # include '-'
        a = re.search(r'^[a-zA-Z0-9_$\-]*', after).group(0)
        text = b + a
        if text:
            view.sel().clear()
            view.sel().add(Region(pos-len(b), pos+len(a)))
        return text, is_symbol