Python sublime.Region() Examples

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

Example 1
Project: NeoVintageous   Author: NeoVintageous   File: utils.py    (license) View Source Project 8 votes vote down vote up
def regions_transformer(view, f):
    sels = list(view.sel())
    new = []
    for sel in sels:
        region = f(view, sel)
        if not isinstance(region, Region):
            raise TypeError('Region required')
        new.append(region)
    view.sel().clear()
    view.sel().add_all(new)


# TODO IMPORTANT was refactored from a module that removed vi/constants.py ...
#       but required by lib/cmds/actions.py module. This can
#       probably be refactored to use regions_transformer(), in
#       fact this function probably causes some bugs becayse
#       regions_transformer() is newer but this function was
#       looks like it was never updated. 
Example 2
Project: NeoVintageous   Author: NeoVintageous   File: utils.py    (license) View Source Project 6 votes vote down vote up
def resize_visual_region(r, b):
    """
    Define a new visual mode region.

    Returns a region where x.a != x.b.

    @r
      Existing region.
    @b
      New end point.
    """
    if b < r.a:
        if r.b > r.a:
            return Region(r.a + 1, b)
        return Region(r.a, b)

    if b > r.a:
        if r.b < r.a:
            return Region(r.a - 1, b + 1)
        return Region(r.a, b + 1)

    return Region(b, b + 1) 
Example 3
Project: NeoVintageous   Author: NeoVintageous   File: ex_location.py    (license) View Source Project 6 votes vote down vote up
def reverse_search(view, what, start=0, end=-1, flags=0):
    """Do binary search to find `what` walking backwards in the buffer."""
    if end == -1:
        end = view.size()
    end = find_eol(view, view.line(end).a)

    last_match = None

    lo, hi = start, end
    while True:
        middle = (lo + hi) / 2
        line = view.line(middle)
        middle, eol = find_bol(view, line.a), find_eol(view, line.a)  # FIXME # noqa: F841

        if search_in_range(view, what, middle, hi, flags):
            lo = middle
        elif search_in_range(view, what, lo, middle - 1, flags):
            hi = middle - 1

        # Don't search forever the same line.
        if last_match and line.contains(last_match):
            match = find_last_match(view, what, lo, hi, flags=flags)
            return view.rowcol(match.begin())[0] + 1

        last_match = sublime.Region(line.begin(), line.end()) 
Example 4
Project: NeoVintageous   Author: NeoVintageous   File: nodes.py    (license) View Source Project 6 votes vote down vote up
def resolve(self, view):
        """Return a representing the Vim line range that the ex command should operate on."""
        start = self.resolve_line_reference(view, self.start or [TokenDot()])

        if not self.separator:
            if start == -1:
                return Region(-1, -1)

            if len(self.start) == 1 and isinstance(self.start[0], TokenPercent):
                return Region(0, view.size())

            return view.full_line(view.text_point(start, 0))

        new_start = start if self.separator == ';' else 0
        end = self.resolve_line_reference(view, self.end or [TokenDot()], current=new_start)

        return view.full_line(Region(view.text_point(start, 0), view.text_point(end, 0))) 
Example 5
Project: NeoVintageous   Author: NeoVintageous   File: surround.py    (license) View Source Project 6 votes vote down vote up
def run(self, edit, mode=None, surround_with='"', count=1, motion=None):
        def f(view, s):
            if mode == INTERNAL_NORMAL_MODE:
                self.surround(edit, s, surround_with)
                return Region(s.begin())
            elif mode in (VISUAL_MODE, VISUAL_BLOCK_MODE):
                self.surround(edit, s, surround_with)
                return Region(s.begin())

            return s

        if not motion and not self.view.has_non_empty_selection_region():
            self.enter_normal_mode(mode)
            raise ValueError('motion required')

        if mode == INTERNAL_NORMAL_MODE:
            self.view.run_command(motion['motion'], motion['motion_args'])

        if surround_with:
            _regions_transformer_reversed(self.view, f)

        self.enter_normal_mode(mode) 
Example 6
Project: NeoVintageous   Author: NeoVintageous   File: ex_actions.py    (license) View Source Project 6 votes vote down vote up
def do_append(self, parsed_command):
        if parsed_command.command.target_file:
            self.do_append_to_file(parsed_command)
            return

        r = None
        if parsed_command.line_range.is_empty:
            # If the user didn't provide any range data, Vim appends whe whole buffer.
            r = Region(0, self._view.size())
        else:
            r = parsed_command.line_range.resolve(self._view)

        text = self._view.substr(r)
        text = text if text.startswith('\n') else '\n' + text

        location = resolve_insertion_point_at_b(first_sel(self._view))

        self._view.run_command('append', {'characters': text})

        utils.replace_sel(self._view, Region(self._view.line(location).a))

        self.enter_normal_mode(mode=self.state.mode)
        self.state.enter_normal_mode() 
Example 7
Project: NeoVintageous   Author: NeoVintageous   File: vi_motions.py    (license) View Source Project 6 votes vote down vote up
def on_change(self, s):
        state = self.state
        flags = self.calculate_flags()
        self.view.erase_regions('vi_inc_search')
        next_hit = find_wrapping(self.view,
                                 term=s,
                                 start=self.view.sel()[0].b + 1,
                                 end=self.view.size(),
                                 flags=flags,
                                 times=state.count)
        if next_hit:
            if state.mode == modes.VISUAL:
                next_hit = Region(self.view.sel()[0].a, next_hit.a + 1)

            self.view.add_regions('vi_inc_search', [next_hit], 'string.search', '', DRAW_NO_OUTLINE)

            if not self.view.visible_region().contains(next_hit.b):
                self.view.show(next_hit.b) 
Example 8
Project: NeoVintageous   Author: NeoVintageous   File: vi_motions.py    (license) View Source Project 6 votes vote down vote up
def run(self, mode=None, count=1):
        def f(view, s):
            if mode == modes.NORMAL:
                return Region(0)
            elif mode == modes.VISUAL:
                if s.a < s.b:
                    return Region(s.a + 1, 0)
                else:
                    return Region(s.a, 0)
            elif mode == modes.INTERNAL_NORMAL:
                return Region(view.full_line(s.b).b, 0)
            elif mode == modes.VISUAL_LINE:
                if s.a < s.b:
                    return Region(0, s.b)
                else:
                    return Region(0, s.a)
            return s

        self.view.window().run_command('_vi_add_to_jump_list')
        regions_transformer(self.view, f)
        self.view.window().run_command('_vi_add_to_jump_list') 
Example 9
Project: NeoVintageous   Author: NeoVintageous   File: vi_motions.py    (license) View Source Project 6 votes vote down vote up
def run(self, mode=None, count=None):
        def f(view, s):
            if mode == modes.NORMAL:
                pt = eof
                if not view.line(eof).empty():
                    pt = utils.previous_non_white_space_char(view, eof - 1, white_space='\n')
                return Region(pt, pt)
            elif mode == modes.VISUAL:
                return Region(s.a, eof)
            elif mode == modes.INTERNAL_NORMAL:
                begin = view.line(s.b).a
                begin = max(0, begin - 1)
                return Region(begin, eof)
            elif mode == modes.VISUAL_LINE:
                return Region(s.a, eof)

            return s

        self.view.window().run_command('_vi_add_to_jump_list')
        eof = self.view.size()
        regions_transformer(self.view, f)
        self.view.window().run_command('_vi_add_to_jump_list') 
Example 10
Project: NeoVintageous   Author: NeoVintageous   File: vi_motions.py    (license) View Source Project 6 votes vote down vote up
def run(self, count=None, mode=None):
        def f(view, s):
            if mode == modes.NORMAL:
                non_ws = utils.next_non_white_space_char(view, target)
                return Region(non_ws, non_ws)
            elif mode == modes.INTERNAL_NORMAL:
                return Region(s.a + 1, target)
            elif mode == modes.VISUAL:
                new_target = utils.next_non_white_space_char(view, target)
                return Region(s.a + 1, new_target)
            else:
                return s

        r = self.view.visible_region()
        row, _ = self.view.rowcol(r.a)
        row += count + 1

        target = self.view.text_point(row, 0)

        regions_transformer(self.view, f)
        self.view.show(target) 
Example 11
Project: NeoVintageous   Author: NeoVintageous   File: vi_motions.py    (license) View Source Project 6 votes vote down vote up
def run(self, count=1, mode=None):
        def do_motion(view, s):
            if mode == modes.NORMAL:
                pt = word_reverse(self.view, s.b, count, big=True)
                return Region(pt)

            elif mode == modes.INTERNAL_NORMAL:
                pt = word_reverse(self.view, s.b, count, big=True)
                return Region(s.a, pt)

            elif mode in (modes.VISUAL, modes.VISUAL_BLOCK):
                if s.a < s.b:
                    pt = word_reverse(self.view, s.b - 1, count, big=True)
                    if pt < s.a:
                        return Region(s.a + 1, pt)
                    return Region(s.a, pt + 1)
                elif s.b < s.a:
                    pt = word_reverse(self.view, s.b, count, big=True)
                    return Region(s.a, pt)

            return s

        regions_transformer(self.view, do_motion) 
Example 12
Project: NeoVintageous   Author: NeoVintageous   File: vi_motions.py    (license) View Source Project 6 votes vote down vote up
def run(self, count=None, mode=None):
        def f(view, s):
            a = s.a
            b = s.b
            if s.size() > 0:
                a = resolve_insertion_point_at_a(s)
                b = resolve_insertion_point_at_b(s)

            bol = self.view.line(b).a
            bol = utils.next_non_white_space_char(self.view, bol, white_space='\t ')

            if mode == modes.NORMAL:
                return Region(bol)
            elif mode == modes.INTERNAL_NORMAL:
                # The character at the "end" of the region is skipped in both
                # forward and reverse cases, so unlike other regions, no need to add 1 to it
                return Region(a, bol)
            elif mode == modes.VISUAL:
                return utils.new_inclusive_region(a, bol)
            else:
                return s

        regions_transformer(self.view, f) 
Example 13
Project: NeoVintageous   Author: NeoVintageous   File: vi_motions.py    (license) View Source Project 6 votes vote down vote up
def run(self, count=1, mode=None):
        def f(view, s):
            if mode == modes.NORMAL:
                eol = view.line(s.b).b
                return Region(eol - 1, eol - 1)

            elif mode == modes.VISUAL:
                eol = None
                if s.a < s.b:
                    eol = view.line(s.b - 1).b
                    return Region(s.a, eol)
                else:
                    eol = view.line(s.b).b
                    if eol > s.a:
                        return Region(s.a - 1, eol)
                    return Region(s.a, eol)

            elif mode == modes.INTERNAL_NORMAL:
                eol = view.line(s.b).b
                return Region(s.a, eol)

            return s

        regions_transformer(self.view, f) 
Example 14
Project: NeoVintageous   Author: NeoVintageous   File: vi_motions.py    (license) View Source Project 6 votes vote down vote up
def run(self, mode=None, extend=False, count=None):

        def f(view, s):
            if mode == modes.NORMAL:
                return next

            elif mode == modes.VISUAL:
                return Region(s.a, next.b)

            elif mode == modes.INTERNAL_NORMAL:
                return Region(s.a, next.b)

            elif mode == modes.VISUAL_LINE:
                return Region(s.a, self.view.full_line(next.b).b)

            return s

        next, scroll_amount = self.next_half_page(count)
        regions_transformer(self.view, f) 
Example 15
Project: NeoVintageous   Author: NeoVintageous   File: vi_motions.py    (license) View Source Project 6 votes vote down vote up
def run(self, mode=None, count=1):
        def to_word_end(view, s):
            if mode == modes.NORMAL:
                pt = word_end_reverse(view, s.b, count)
                return Region(pt)
            elif mode in (modes.VISUAL, modes.VISUAL_BLOCK):
                if s.a < s.b:
                    pt = word_end_reverse(view, s.b - 1, count)
                    if pt > s.a:
                        return Region(s.a, pt + 1)
                    return Region(s.a + 1, pt)
                pt = word_end_reverse(view, s.b, count)
                return Region(s.a, pt)
            return s

        regions_transformer(self.view, to_word_end) 
Example 16
Project: NeoVintageous   Author: NeoVintageous   File: vi_motions.py    (license) View Source Project 6 votes vote down vote up
def run(self, mode=None, count=1):
        def to_word_end(view, s):
            if mode == modes.NORMAL:
                pt = word_end_reverse(view, s.b, count, big=True)
                return Region(pt)
            elif mode in (modes.VISUAL, modes.VISUAL_BLOCK):
                if s.a < s.b:
                    pt = word_end_reverse(view, s.b - 1, count, big=True)
                    if pt > s.a:
                        return Region(s.a, pt + 1)
                    return Region(s.a + 1, pt)
                pt = word_end_reverse(view, s.b, count, big=True)
                return Region(s.a, pt)
            return s

        regions_transformer(self.view, to_word_end) 
Example 17
Project: NeoVintageous   Author: NeoVintageous   File: vi_motions.py    (license) View Source Project 6 votes vote down vote up
def run(self, mode=None, count=1):

        def f(view, s):
            # TODO: must skip empty paragraphs.
            sen = self.find_previous_sentence_end(s)

            if mode == modes.NORMAL:
                return Region(sen.a, sen.a)

            elif mode == modes.VISUAL:
                return Region(s.a + 1, sen.a + 1)

            elif mode == modes.INTERNAL_NORMAL:
                return Region(s.a, sen.a + 1)

            return s

        regions_transformer(self.view, f) 
Example 18
Project: NeoVintageous   Author: NeoVintageous   File: vi_motions.py    (license) View Source Project 6 votes vote down vote up
def find_next_sentence_end(self, r):
        sen = r
        non_ws = utils.next_non_white_space_char(self.view, sen.b, '\t \n')
        sen = Region(non_ws, non_ws)
        while True:
            sen = self.view.expand_by_class(sen, CLASS_PUNCTUATION_START | CLASS_LINE_END)
            if (sen.b == self.view.size() or
                (self.view.substr(Region(sen.b, sen.b + 2)).endswith(('. ', '.\t'))) or
                (self.view.substr(Region(sen.b, sen.b + 1)).endswith(('?', '!'))) or
                (self.view.substr(self.view.line(sen.b)).strip() == '')):  # FIXME # noqa: E129
                    if self.view.substr(sen.b) in '.?!':
                        return Region(sen.a, sen.b + 1)
                    else:
                        if self.view.line(sen.b).empty():
                            return Region(sen.a, sen.b)
                        else:
                            return self.view.full_line(sen.b) 
Example 19
Project: NeoVintageous   Author: NeoVintageous   File: vi_motions.py    (license) View Source Project 6 votes vote down vote up
def run(self, mode=None, count=1):
        def f(view, s):
            # TODO: must skip empty paragraphs.
            sen = self.find_next_sentence_end(s)

            if mode == modes.NORMAL:
                target = min(sen.b, view.size() - 1)
                return Region(target, target)

            elif mode == modes.VISUAL:
                # TODO: Must encompass new line char too?
                return Region(s.a, sen.b)

            elif mode == modes.INTERNAL_NORMAL:
                return Region(s.a, sen.b)

            return s

        regions_transformer(self.view, f) 
Example 20
Project: NeoVintageous   Author: NeoVintageous   File: vi_motions.py    (license) View Source Project 6 votes vote down vote up
def on_change(self, s):
        flags = self.calculate_flags()
        self.view.erase_regions('vi_inc_search')
        state = self.state
        occurrence = reverse_find_wrapping(self.view,
                                           term=s,
                                           start=0,
                                           end=self.view.sel()[0].b,
                                           flags=flags,
                                           times=state.count)
        if occurrence:
            if state.mode == modes.VISUAL:
                occurrence = Region(self.view.sel()[0].a, occurrence.a)

            self.view.add_regions('vi_inc_search', [occurrence], 'string.search', '', DRAW_NO_OUTLINE)

            if not self.view.visible_region().contains(occurrence):
                self.view.show(occurrence) 
Example 21
Project: NeoVintageous   Author: NeoVintageous   File: vi_motions.py    (license) View Source Project 6 votes vote down vote up
def run(self, mode=None, count=1):
        self.view.run_command('_vi_j', {'mode': mode, 'count': count})

        def advance(view, s):
            if mode == modes.NORMAL:
                pt = utils.next_non_white_space_char(view, s.b,
                                                     white_space=' \t')
                return Region(pt)
            elif mode == modes.VISUAL:
                if s.a < s.b:
                    pt = utils.next_non_white_space_char(view, s.b - 1,
                                                         white_space=' \t')
                    return Region(s.a, pt + 1)
                pt = utils.next_non_white_space_char(view, s.b,
                                                     white_space=' \t')
                return Region(s.a, pt)
            return s

        regions_transformer(self.view, advance) 
Example 22
Project: NeoVintageous   Author: NeoVintageous   File: vi_motions.py    (license) View Source Project 6 votes vote down vote up
def run(self, mode=None, count=1):
        self.view.run_command('_vi_k', {'mode': mode, 'count': count})

        def advance(view, s):
            if mode == modes.NORMAL:
                pt = utils.next_non_white_space_char(view, s.b,
                                                     white_space=' \t')
                return Region(pt)
            elif mode == modes.VISUAL:
                if s.a < s.b:
                    pt = utils.next_non_white_space_char(view, s.b - 1,
                                                         white_space=' \t')
                    return Region(s.a, pt + 1)
                pt = utils.next_non_white_space_char(view, s.b,
                                                     white_space=' \t')
                return Region(s.a, pt)
            return s

        regions_transformer(self.view, advance) 
Example 23
Project: NeoVintageous   Author: NeoVintageous   File: vi_motions.py    (license) View Source Project 6 votes vote down vote up
def run(self, mode=None, count=1, char=None):
        def move(view, s):
            reg = find_prev_lone_bracket(self.view, s.b, brackets)
            if reg is not None:
                return Region(reg.a)
            return s

        if mode != modes.NORMAL:
            self.enter_normal_mode(mode=mode)
            utils.blink()
            return

        brackets = self.BRACKETS.get(char)
        if brackets is None:
            utils.blink()
            return

        regions_transformer(self.view, move)


# https://vimhelp.appspot.com/diff.txt.html#[c 
Example 24
Project: NeoVintageous   Author: NeoVintageous   File: vi_actions.py    (license) View Source Project 6 votes vote down vote up
def run(self, count=1):
        for i in range(count):
            self._view.run_command('undo')

        if self._view.has_non_empty_selection_region():
            def reverse(view, s):
                return Region(s.end(), s.begin())

            # TODO: xpos is misaligned after this.
            regions_transformer(self._view, reverse)
            # FIXME: why from modes.VISUAL?
            self.window.run_command('_enter_normal_mode', {
                'mode': modes.VISUAL
            })

        # If we yy, then u, we might end up with outlined regions if we
        # don't erase them here, because ST will restore them when undoing.
        self._view.erase_regions('vi_yy_target')


# https://vimhelp.appspot.com/undo.txt.html#CTRL-R 
Example 25
Project: NeoVintageous   Author: NeoVintageous   File: vi_actions.py    (license) View Source Project 6 votes vote down vote up
def run(self, edit, mode=None):
        def f(view, s):
            if mode == modes.VISUAL_LINE:
                return Region(s.a, s.b)
            else:
                if s.empty() and (s.b == self.view.size()):
                    utils.blink()
                    return s

                # Extending from s.a to s.b because we may be looking at
                # selections with len>0. For example, if it's been created
                # using the mouse. Normally, though, the selection will be
                # empty when we reach here.
                end = s.b
                # Only extend .b by 1 if we're looking at empty sels.
                if not view.has_non_empty_selection_region():
                    end += 1
                return Region(s.a, end)

        regions_transformer(self.view, f) 
Example 26
Project: NeoVintageous   Author: NeoVintageous   File: vi_actions.py    (license) View Source Project 6 votes vote down vote up
def run(self, edit, mode=None):
        def f(view, s):
            if mode == modes.VISUAL:
                if s.a < s.b:
                    if view.substr(s.b - 1) != '\n':
                        return Region(view.line(s.a).a, view.full_line(s.b - 1).b)
                    else:
                        return Region(view.line(s.a).a, s.b)
                else:
                    if view.substr(s.a - 1) != '\n':
                        return Region(view.full_line(s.a - 1).b, view.line(s.b).a)
                    else:
                        return Region(s.a, view.line(s.b).a)
            else:
                return view.full_line(s.b)

        regions_transformer(self.view, f) 
Example 27
Project: NeoVintageous   Author: NeoVintageous   File: vi_actions.py    (license) View Source Project 6 votes vote down vote up
def run(self, edit, mode=None, count=1, motion=None, register=None):
        def f(view, s):
            return Region(s.end(), s.begin())

        if mode == modes.INTERNAL_NORMAL:
            if motion is None:
                raise ValueError('bad args')
            self.view.run_command(motion['motion'], motion['motion_args'])
            self.outline_target()

        elif mode not in (modes.VISUAL, modes.VISUAL_LINE, modes.VISUAL_BLOCK):
            return

        state = self.state
        state.registers.yank(self, register)
        regions_transformer(self.view, f)
        self.enter_normal_mode(mode)


# https://vimhelp.appspot.com/change.txt.html#d 
Example 28
Project: NeoVintageous   Author: NeoVintageous   File: vi_actions.py    (license) View Source Project 6 votes vote down vote up
def run(self, edit, mode=None, count=1, register=None):
        def f(view, s):
            if mode == modes.INTERNAL_NORMAL:
                if count == 1:
                    if view.line(s.b).size() > 0:
                        eol = view.line(s.b).b
                        return Region(s.b, eol)
                    return s
            return s

        self.save_sel()
        regions_transformer(self.view, f)

        state = self.state
        state.registers.yank(self)

        self.view.run_command('left_delete')

        self.enter_normal_mode(mode) 
Example 29
Project: NeoVintageous   Author: NeoVintageous   File: vi_actions.py    (license) View Source Project 6 votes vote down vote up
def run(self, edit, mode=None, count=None):
        def motion(view, s):
            if mode != modes.INTERNAL_NORMAL:
                return s

            if count <= 1:
                return s

            a = utils.get_bol(view, s.a)
            pt = view.text_point(utils.row_at(view, a) + (count - 1), 0)
            return Region(a, utils.get_eol(view, pt))

        def action(view, s):
            bol = utils.get_bol(view, s.begin())
            pt = utils.next_non_white_space_char(view, bol, white_space='\t ')
            return Region(pt)

        regions_transformer(self.view, motion)
        self.view.run_command('unindent')
        regions_transformer(self.view, action) 
Example 30
Project: NeoVintageous   Author: NeoVintageous   File: vi_actions.py    (license) View Source Project 6 votes vote down vote up
def run(self, edit, mode=None, count=1):
        def f(view, s):
            return Region(s.begin())

        def select(view):
            s0 = utils.first_sel(self.view)
            end_row = utils.row_at(view, s0.b) + (count - 1)
            view.sel().clear()
            view.sel().add(Region(s0.begin(), view.text_point(end_row, 1)))

        if count > 1:
            select(self.view)

        self.view.run_command('reindent', {'force_indent': False})
        regions_transformer(self.view, f)
        self.enter_normal_mode(mode) 
Example 31
Project: NeoVintageous   Author: NeoVintageous   File: vi_actions.py    (license) View Source Project 6 votes vote down vote up
def run(self, edit, mode=None, count=1):
        def f(view, s):
            bol = utils.get_bol(view, s.begin())
            pt = utils.next_non_white_space_char(view, bol, white_space='\t ')
            return Region(pt)

        def select(view):
            s0 = utils.first_sel(view)
            end_row = utils.row_at(view, s0.b) + (count - 1)
            utils.replace_sel(view, Region(s0.begin(), view.text_point(end_row, 1)))

        if count > 1:
            select(self.view)

        self.view.run_command('indent')
        regions_transformer(self.view, f)
        self.enter_normal_mode(mode) 
Example 32
Project: NeoVintageous   Author: NeoVintageous   File: vi_actions.py    (license) View Source Project 6 votes vote down vote up
def run(self, edit, mode=None, count=1, motion=None):
        def f(view, s):
            return Region(s.begin())

        # Note: Vim does not unindent in visual block mode.

        if motion:
            self.view.run_command(motion['motion'], motion['motion_args'])
        elif mode not in (modes.VISUAL, modes.VISUAL_LINE):
            utils.blink()
            return

        for i in range(count):
            self.view.run_command('unindent')

        regions_transformer(self.view, f)
        self.enter_normal_mode(mode) 
Example 33
Project: NeoVintageous   Author: NeoVintageous   File: vi_actions.py    (license) View Source Project 6 votes vote down vote up
def run(self, edit, count=1, mode=None, motion=None):
        def select(view, s):
            if mode == modes.VISUAL:
                return Region(s.end(), s.begin())
            return Region(s.begin(), s.end() + count)

        def after(view, s):
            return Region(s.begin())

        regions_transformer(self.view, select)
        self.view.run_command('swap_case')

        if mode in (modes.VISUAL, modes.VISUAL_LINE, modes.VISUAL_BLOCK):
            regions_transformer(self.view, after)

        self.enter_normal_mode(mode) 
Example 34
Project: NeoVintageous   Author: NeoVintageous   File: vi_actions.py    (license) View Source Project 6 votes vote down vote up
def run(self, edit, mode=None, count=1):
        def select(view, s):
            line = view.line(s.b)

            return Region(line.end(), line.begin())

        def to_lower(view, s):
            view.replace(edit, s, view.substr(s).lower())
            return s

        regions_transformer(self.view, select)
        regions_transformer(self.view, to_lower)
        self.enter_normal_mode(mode)


# Non-standard command. After a search has been performed via '/' or '?',
# selects all matches and enters select mode. 
Example 35
Project: NeoVintageous   Author: NeoVintageous   File: vi_actions.py    (license) View Source Project 6 votes vote down vote up
def run(self, edit, mode=None, count=1):
        def f(view, s):
            if mode == modes.INTERNAL_NORMAL:
                view.run_command('toggle_comment')
                if utils.row_at(self.view, s.a) != utils.row_at(self.view, self.view.size()):
                    pt = utils.next_non_white_space_char(view, s.a, white_space=' \t')
                else:
                    pt = utils.next_non_white_space_char(view,
                                                         self.view.line(s.a).a,
                                                         white_space=' \t')

                return Region(pt, pt)
            return s

        self.view.run_command('_vi_gcc_motion', {'mode': mode, 'count': count})

        state = self.state
        state.registers.yank(self)

        row = [self.view.rowcol(s.begin())[0] for s in self.view.sel()][0]
        regions_transformer_reversed(self.view, f)
        self.view.sel().clear()
        self.view.sel().add(Region(self.view.text_point(row, 0))) 
Example 36
Project: Sublime-minihtml-Preview   Author: ehuss   File: minihtml_preview.py    (MIT License) View Source Project 6 votes vote down vote up
def on_modified_async(self):
        output_id = self.view.settings().get('minihtml_preview_output_view_id')
        output_view = next(view for view in self.view.window().views()
            if view.id() == output_id)
        content = self.view.substr(sublime.Region(0, self.view.size()))

        buffer_id = output_view.buffer_id()
        if buffer_id in self.phantom_sets:
            ps = self.phantom_sets[buffer_id]
        else:
            ps = sublime.PhantomSet(output_view, 'minihtml_preview_phantom')
            self.phantom_sets[buffer_id] = ps

        p = sublime.Phantom(sublime.Region(0), content,
                            sublime.LAYOUT_BLOCK, _on_navigate)
        ps.update([p]) 
Example 37
Project: hyperhelp   Author: OdatNurd   File: output_view.py    (MIT License) View Source Project 6 votes vote down vote up
def _restore_state(view, state):
    """
    Restore the selection and viewport position that was previously saved via
    _save_state(). If the last selection was at the end of the buffer, put it
    back there even if the size of the buffer has changed so that future append
    operations will work.
    """
    size = state[0]
    sel = state[1]
    vpos = state[2]

    # If the last selection was at the end of the buffer, replace that
    # selection with the new end of the buffer so the relative position remains
    # the same.
    if sublime.Region(size, size) == sel[-1]:
        sel[-1] = sublime.Region(view.size(), view.size())

    view.sel().clear()
    for region in sel:
        view.sel().add(region)

    view.set_viewport_position(vpos, False) 
Example 38
Project: hyperhelp   Author: OdatNurd   File: operations.py    (MIT License) View Source Project 6 votes vote down vote up
def focus_on(view, position):
    """
    Focus the given help view on the provided position to ensure that is is
    visible. This alters the selection to the given position.

    If position is a point, the view is focused on that point and the cursor is
    placed there. If it is a Region, the region is selected and the cursor is
    left at the beginning of the region instead of at the end.
    """
    if isinstance(position, int):
        position = sublime.Region(position, position)
    else:
        position = sublime.Region(position.end(), position.begin())

    view.show_at_center(position)
    view.sel().clear()
    view.sel().add(position)

    # Hack to make the view update properly. See:
    #    https://github.com/SublimeTextIssues/Core/issues/485
    view.add_regions("_hh_rk", [], "", "", sublime.HIDDEN)
    view.erase_regions("_hh_rk") 
Example 39
Project: VHDL-Mode   Author: Remillard   File: vhdl_mode.py    (MIT License) View Source Project 6 votes vote down vote up
def run(self, edit):
        """Sublime Text plugin run method."""
        # Note, if one changes the header, this might need to change too.
        pattern = util.get_vhdl_setting(self, 'vhdl-modified-time-string')
        region = self.view.find(pattern, 0)
        #print('Region Diagnostics')
        #print('------------------')
        #print('Begin: {}'.format(region.begin()))
        #print('End:   {}'.format(region.end()))
        #print('Empty? {}'.format(region.empty()))
        if not region.empty():
            region = self.view.line(region)
            date = time.ctime(time.time())
            new_mtime = pattern + '{}'.format(date)
            self.view.replace(edit, region, new_mtime)
            print('vhdl-mode: Updated last modified time.')
        else:
            print('vhdl-mode: No last modified time field found.')

#---------------------------------------------------------------- 
Example 40
Project: TerminalView   Author: Wramberg   File: sublime_terminal_buffer.py    (MIT License) View Source Project 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 41
Project: TerminalView   Author: Wramberg   File: sublime_terminal_buffer.py    (MIT License) View Source Project 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 42
Project: sublime-text-3-packages   Author: nickjj   File: commands.py    (MIT License) View Source Project 6 votes vote down vote up
def select_lint_region(cls, view, region):
        """
        Select and scroll to the first marked region that contains region.

        If none are found, the beginning of region is used. The view is
        centered on the calculated region and the region is selected.

        """

        marked_region = cls.find_mark_within(view, region)

        if marked_region is None:
            marked_region = sublime.Region(region.begin(), region.begin())

        sel = view.sel()
        sel.clear()
        sel.add(marked_region)

        # There is a bug in ST3 that prevents the selection from changing
        # when a quick panel is open and the viewport does not change position,
        # so we call our own custom method that works around that.
        util.center_region_in_view(marked_region, view) 
Example 43
Project: sublime-text-3-packages   Author: nickjj   File: file.py    (MIT License) View Source Project 6 votes vote down vote up
def scan(self):
    """Scan the file for colours and add/remove regions appropriately"""

    # Return a list of all the line regions in the current file
    if self.action == 'update':
      regions = [self.view.line(s) for s in self.view.sel()]
    else:
      regions = self.view.lines(Region(0, self.view.size()))

    for region in regions:
      line = Line(self.view, region, self.id)
      if line.has_color():
        line.add_region()
      else:
        try:
          self.view.erase_regions("gutter_color_%s" % region.a)
        except:
          pass 
Example 44
Project: PhaserSublimePackage   Author: PhaserEditor2D   File: tern.py    (license) View Source Project 6 votes vote down vote up
def buffer_fragment(view, pos):
  region = None
  for js_region in view.find_by_selector("source.js"):
    if js_region.a <= pos and js_region.b >= pos:
      region = js_region
      break
  if region is None: return sublime.Region(pos, pos)

  start = view.line(max(region.a, pos - 1000)).a
  if start < pos - 1500: start = pos - 1500
  cur = start
  min_indent = 10000
  while True:
    next = view.find("\\bfunction\\b", cur)
    if next is None or next.b > pos or (next.a == -1 and next.b == -1): break
    line = view.line(next.a)
    if line.a < pos - 1500: line = sublime.Region(pos - 1500, line.b)
    indent = count_indentation(view.substr(line))
    if indent < min_indent:
      min_indent = indent
      start = line.a
    cur = line.b
  return sublime.Region(start, min(pos + 500, region.b)) 
Example 45
Project: PhaserSublimePackage   Author: PhaserEditor2D   File: tern.py    (license) View Source Project 6 votes vote down vote up
def locate_call(view):
  sel = view.sel()[0]
  if sel.a != sel.b: return (None, 0)
  context = view.substr(sublime.Region(max(0, sel.b - 500), sel.b))
  pos = len(context)
  depth = argpos = 0
  while pos > 0:
    pos -= 1
    ch = context[pos]
    if ch == "}" or ch == ")" or ch == "]":
      depth += 1
    elif ch == "{" or ch == "(" or ch == "[":
      if depth > 0: depth -= 1
      elif ch == "(": return (pos + sel.b - len(context), argpos)
      else: return (None, 0)
    elif ch == "," and depth == 0:
      argpos += 1
  return (None, 0) 
Example 46
Project: chains   Author: hc-12   File: Chains.py    (license) View Source Project 6 votes vote down vote up
def expand_whole_word(view, region):
    """increase point/region until reaches \s, \n
       and DONE_SYMBOL, returns word region"""
    # deal with edge cases where the cursor is inbetween two dates
    if region.empty() and view.substr(region.b) == ' ':
        # peek to the right for any characters
        r = sublime.Region(region.a, region.b+2)
        c = view.substr(r).strip()

        if c:
            return expand_end_of_word(view, r)

        # peek to the left for any characters
        r = sublime.Region(region.a-2, region.b)
        c = view.substr(r).strip()

        if c:
            return expand_beginning_of_word(view, r)

    return expand_end_of_word(view, region) 
Example 47
Project: SubVale   Author: ValeLint   File: Vale.py    (license) View Source Project 6 votes vote down vote up
def run(self, edit):
        """Run vale on the user-indicated buffer.
        """
        path = self.view.file_name()

        if not Settings.vale_exists():
            debug('binary not found!')
            return
        elif not path or self.view.is_scratch():
            debug('invalid path: {0}!'.format(path))
            return

        debug('running vale on {0}'.format(self.view.settings().get('syntax')))
        cmd = [Settings.get('vale_binary'), '--output=JSON']
        buf = self.view.substr(sublime.Region(0, self.view.size()))
        output, error = run_on_buf(cmd, buf, path)
        if error:
            debug(error)
            return

        self.show_alerts(output) 
Example 48
Project: SubVale   Author: ValeLint   File: Vale.py    (license) View Source Project 6 votes vote down vote up
def show_alerts(self, data):
        """Add alert regions to the view.
        """
        Settings.clear_on_hover()
        regions = []
        for f, alerts in data.items():
            for a in alerts:
                start = self.view.text_point(a['Line'] - 1, 0)
                loc = (start + a['Span'][0] - 1, start + a['Span'][1])
                regions.append(sublime.Region(*loc))
                Settings.on_hover.append({
                    'region': regions[-1], 'HTML': self._make_content(a),
                    'view_id': self.view.id(), 'level': a['Severity'],
                    'msg': a['Message']
                })
        self.view.add_regions('Vale Alerts', regions,
                              Settings.get('vale_highlight_scope'),
                              Settings.get('vale_icon'),
                              Settings.get_draw_style()) 
Example 49
Project: DXMate   Author: jtowers   File: languageServer.py    (license) View Source Project 6 votes vote down vote up
def notify_did_change(view: sublime.View):
    if util.is_apex_file(view) and view.buffer_id() in pending_buffer_changes:
        del pending_buffer_changes[view.buffer_id()]
    if client:
        document_state = get_document_state(view.file_name())
        uri = util.filename_to_uri(view.file_name())
        params = {
            "textDocument": {
                "uri": uri,
                # "languageId": config.languageId, clangd does not like this field, but no server uses it?
                "version": document_state.inc_version(),
            },
            "contentChanges": [{
                "text": view.substr(sublime.Region(0, view.size()))
            }]
        }
        client.send_notification(Notification.didChange(params)) 
Example 50
Project: DXMate   Author: jtowers   File: dxmate.py    (license) View Source Project 6 votes vote down vote up
def run(self, edit):
        self.selection = ''
        for region in self.view.sel():
            if not region.empty():
                self.selection += self.view.substr(region)
        if self.selection == '':
            self.selection = self.view.substr(sublime.Region(0, self.view.size()))
        self.file_path = os.path.join(util.dxProjectFolder(), '.sfdx', 'tmpFile.cls')
        with open(self.file_path, 'w+') as file_obj:
            file_obj.write(self.selection)
        printer.show()
        self.namespace = input
        t = threading.Thread(target=self.run_command)
        t.start()
        t.printer = printer
        t.process_id = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())
        ThreadProgress(t, 'Running anonymous apex', 'Anonymous apex run')
        printer.write('\nRunning anonymous apex')
        printer.write('\nResult: ')
        PanelThreadProgress(t, 'Anonymous apex run')