Ejemplo n.º 1
0
 def ignore_case(self, value):
     if value and not self.pattern[0].flags & re.IGNORECASE:
         find = self.pattern[0]
         find = RegexPattern(find, find.flags | re.IGNORECASE)
         self.pattern = (find, self.pattern[1])
     elif not value and self.pattern[0].flags & re.IGNORECASE:
         find = self.pattern[0]
         find = RegexPattern(find, find.flags ^ re.IGNORECASE)
         self.pattern = (find, self.pattern[1])
Ejemplo n.º 2
0
def test_SortLinesController_load_options():
    def test(hist, opts):
        with replace_history() as history:
            history.append(hist)
            ctl = SortLinesController(None)
            eq_(ctl.options._target, SortOptions(**opts))

    yield test, "sort", {}
    yield test, "sort all", {"selection": False}
    yield test, "sort  rev ignore-leading ignore-case /(\d+)([a-z]+)/\2\1/i", {
        "reverse": True,
        "ignore_leading_whitespace": True,
        "ignore_case": True,
        "search_pattern": RegexPattern("(\d+)([a-z]+)"),
        "match_pattern": "\2\1",
    }
    yield test, "sort /(\d+)([a-z]+)/\2\1/i", {
        "search_pattern": RegexPattern("(\d+)([a-z]+)"),
        "match_pattern": "\2\1",
    }
Ejemplo n.º 3
0
class FindOptions(Options):

    DEFAULTS = dict(
        pattern=(RegexPattern(), ""),
        action='find_next',
        search_type=REGEX,
        wrap_around=True,
    )

    dependent_key_paths = {
        "match_entire_word":
        ["regular_expression", "search_type", "python_replace"],
        "regular_expression":
        ["match_entire_word", "search_type", "python_replace"],
        "python_replace":
        ["match_entire_word", "search_type", "regular_expression"],
        "search_type":
        ["match_entire_word", "regular_expression", "python_replace"],
        "pattern": ["find_text", "replace_text", "ignore_case"],
        "find_text": ["pattern"],
        "replace_text": ["pattern"],
        "ignore_case": ["pattern"],
    }

    @property
    def find_text(self):
        return self.pattern[0]

    @find_text.setter
    def find_text(self, value):
        value = RegexPattern(value, self.pattern[0].flags)
        self.pattern = (value, self.pattern[1])

    @property
    def replace_text(self):
        return self.pattern[1]

    @replace_text.setter
    def replace_text(self, value):
        self.pattern = (self.pattern[0], value or "")

    @property
    def ignore_case(self):
        return self.pattern[0].flags & re.IGNORECASE

    @ignore_case.setter
    def ignore_case(self, value):
        if value and not self.pattern[0].flags & re.IGNORECASE:
            find = self.pattern[0]
            find = RegexPattern(find, find.flags | re.IGNORECASE)
            self.pattern = (find, self.pattern[1])
        elif not value and self.pattern[0].flags & re.IGNORECASE:
            find = self.pattern[0]
            find = RegexPattern(find, find.flags ^ re.IGNORECASE)
            self.pattern = (find, self.pattern[1])

    @property
    def regular_expression(self):
        return self.search_type == REGEX or self.search_type == REPY

    @regular_expression.setter
    def regular_expression(self, value):
        assert isinstance(value, (int, bool)), value
        if value:
            if self.search_type != REPY:
                self.search_type = REGEX
        elif self.search_type != WORD:
            self.search_type = LITERAL

    @property
    def match_entire_word(self):
        return self.search_type == WORD

    @match_entire_word.setter
    def match_entire_word(self, value):
        assert isinstance(value, (int, bool)), value
        if value or not self.regular_expression:
            self.search_type = WORD if value else LITERAL

    @property
    def python_replace(self):
        return self.search_type == REPY

    @python_replace.setter
    def python_replace(self, value):
        assert isinstance(value, (int, bool)), value
        if value:
            self.search_type = REPY
        elif self.search_type == REPY:
            self.search_type = REGEX

    @property
    def recent_finds(self):
        # HACK global resource
        predicate = make_command_predicate(find)
        items = editxt.app.text_commander.history.iter_matching(predicate)
        result = []
        for i, item in enumerate(items):
            if i < 10:
                result.append(item)
            else:
                break
        return result

    @property
    def recent_replaces(self):
        # DEPRECATED here so nib file can still bind
        return []
Ejemplo n.º 4
0
 def find_text(self, value):
     value = RegexPattern(value, self.pattern[0].flags)
     self.pattern = (value, self.pattern[1])
Ejemplo n.º 5
0
    ACTION_FIND_SELECTED_TEXT,
    ACTION_FIND_SELECTED_TEXT_REVERSE,
])

FORWARD = "FORWARD"
BACKWARD = "BACKWARD"
WRAPTOKEN = "WRAPTOKEN"

REGEX = "regex"
REPY = "python-replace"
LITERAL = "literal"
WORD = "word"


@command(arg_parser=CommandParser(
    Regex('pattern', replace=True, default=(RegexPattern(), "")),
    Choice(('find-next next', 'find_next'),
           ('find-previous previous', 'find_previous'),
           ('replace-one one', 'replace_one'),
           ('replace-all all', 'replace_all'),
           ('replace-in-selection in-selection selection',
            'replace_all_in_selection'),
           ('count-occurrences highlight', 'count_occurrences'),
           name='action'),
    Choice('regex literal word python-replace', name='search_type'),
    Choice(('wrap', True), ('no-wrap', False), name='wrap_around'),
),
         lookup_with_arg_parser=True)
def find(textview, sender, args):
    assert args is not None, sender
    opts = FindOptions(**args.__dict__)
Ejemplo n.º 6
0
 def sort_regex(self):
     if self.regex_sort:
         return (RegexPattern(self.search_pattern), self.match_pattern)
     return (None, None)
Ejemplo n.º 7
0
def test_RegexPattern():
    yield eq_, RegexPattern("a"), RegexPattern("a")
    yield eq_, RegexPattern("a", re.I), RegexPattern("a", re.I)
    yield eq_, RegexPattern("a", re.I), "a"
    yield eq_, "a", RegexPattern("a", re.I)

    def ne(a, b):
        assert a != b, "{!r} == {!r}".format(a, b)

    yield ne, RegexPattern("a", re.I), RegexPattern("b", re.I)
    yield ne, RegexPattern("a", re.I), RegexPattern("a")
    yield ne, RegexPattern("a", re.I), RegexPattern("b")
    yield ne, RegexPattern("a", re.I), "b"
    yield ne, "b", RegexPattern("a", re.I)

    def lt(a, b):
        assert a < b, "{!r} >= {!r}".format(a, b)

    yield lt, RegexPattern("a"), RegexPattern("a", re.I)
Ejemplo n.º 8
0
def test_Regex():
    arg = Regex('regex')
    eq_(str(arg), 'regex')
    eq_(repr(arg), "Regex('regex')")

    def regex_test(text, start, expect, flags=0):
        if isinstance(expect, Exception):

            def check(err):
                eq_(err, expect)

            with assert_raises(type(expect), msg=check):
                arg.consume(text, start)
            return
        value = arg.consume(text, start)
        if expect[0] in [None, (None, None)]:
            eq_(value, expect)
            return
        expr, index = value
        if arg.replace:
            (expr, replace) = expr
            got = ((expr, replace), index)
        else:
            got = (expr, index)
        eq_(got, expect)
        eq_(expr.flags, flags | re.UNICODE | re.MULTILINE)

    test = regex_test
    yield test, '', 0, (None, 0)
    yield test, '/abc/', 0, ('abc', 5)
    yield test, '/abc/ def', 0, ('abc', 6)
    yield test, '/abc/  def', 0, ('abc', 6)
    yield test, '/abc/i def', 0, ('abc', 7), re.I
    yield test, '/abc/is def', 0, ('abc', 8), re.I | re.S
    yield test, '/abc/is  def', 0, ('abc', 8), re.I | re.S
    yield test, 'abc', 0, \
        ParseError("invalid search pattern: 'abc'", arg, 0, 3)
    #('abc', 3)
    yield test, '^abc$', 0, \
        ParseError("invalid search pattern: '^abc$'", arg, 0, 5)
    #('^abc$', 5)
    yield test, '^abc$ def', 0, \
        ParseError("invalid search pattern: '^abc$ def'", arg, 0, 9)
    #('^abc$', 6)
    yield test, '/abc/X def', 0, \
        ParseError('unknown flag: X', arg, 5, 5)

    test = make_placeholder_checker(arg)
    yield test, "", 0, ("regex", 0)
    yield test, "/", 0, ("/", 2)
    yield test, "//", 0, ("", 2)
    yield test, "// ", 0, (None, 3)

    test = make_arg_string_checker(arg)
    yield test, RegexPattern("str"), "/str/"
    yield test, RegexPattern("str", re.I), "/str/i"
    yield test, RegexPattern("/usr/bin"), ":/usr/bin:"
    yield test, RegexPattern("/usr/bin:"), '"/usr/bin:"'
    yield test, RegexPattern(r'''//''\:""'''), r'''://''\:"":'''
    yield test, RegexPattern(r'''//''\\:""'''), r'''://''\\\:"":''', False
    yield test, RegexPattern(r'''\://''""'''), r''':\://''"":'''
    yield test, RegexPattern(r'''\\://''""'''), r''':\\\://''"":''', False
    # pedantic cases with three or more of all except ':'
    yield test, RegexPattern(r'''///'"'::"'"'''), r''':///'"'\:\:"'":''', False
    yield test, RegexPattern(
        r'''///'"':\\:"'"'''), r''':///'"'\:\\\:"'":''', False
    yield test, "str", Error("invalid value: regex='str'")

    arg = Regex('regex', replace=True)
    eq_(repr(arg), "Regex('regex', replace=True)")
    test = regex_test
    yield test, '', 0, ((None, None), 0)
    yield test, '/abc', 0, (('abc', None), 5)
    yield test, '/abc ', 0, (('abc ', None), 6)
    yield test, '/\\\\', 0, (('\\\\', None), 4)
    yield test, '/\\/', 0, (('\\/', None), 4)
    yield test, '"abc', 0, (('abc', None), 5)
    yield test, '"abc"', 0, (('abc', ''), 6)
    yield test, '"abc""', 0, (('abc', ''), 6)
    yield test, '/abc def', 0, (('abc def', None), 9)
    yield test, '/abc/def', 0, (('abc', 'def'), 9)
    yield test, '/abc/def/', 0, (('abc', 'def'), 9)
    yield test, '/abc/def/ def', 0, (('abc', 'def'), 10)
    yield test, '/abc/def/  def', 0, (('abc', 'def'), 10)
    yield test, '/abc/def/i  def', 0, (('abc', 'def'), 11), re.I
    yield test, '/abc/def/is  def', 0, (('abc', 'def'), 12), re.I | re.S
    yield test, '/(', 0, (("(", None), 3)
    yield test, 'abc', 0, \
        ParseError("invalid search pattern: 'abc'", arg, 0, 3)
    yield test, 'abc def', 0, \
        ParseError("invalid search pattern: 'abc def'", arg, 0, 7)
    yield test, '/abc/def/y  def', 0, \
        ParseError('unknown flag: y', arg, 9, 9)
    msg = 'invalid regular expression: unbalanced parenthesis'

    test = make_placeholder_checker(arg)
    yield test, "", 0, ("regex", 0)
    yield test, "/", 0, ("//", 2)
    yield test, "/x/", 0, ("/", 4)
    yield test, "/\\//", 0, ("/", 5)
    yield test, "/x//", 0, ("", 4)

    arg = Regex('regex', replace=True, default=("", ""))
    test = make_placeholder_checker(arg)
    yield test, "", 0, ("regex", 0)
    yield test, "/", 0, ("//", 2)
    yield test, "/x/", 0, ("/", 4)
    yield test, "/\\//", 0, ("/", 5)
    yield test, "/x//", 0, ("", 4)

    test = make_arg_string_checker(arg)
    yield test, (RegexPattern("str"), 'abc'), "/str/abc/"
    yield test, (RegexPattern("str", re.I), 'abc'), "/str/abc/i"
    yield test, (RegexPattern("/usr/bin"), "abc"), ":/usr/bin:abc:"
    yield test, (RegexPattern("/usr/bin:"), ":"), '"/usr/bin:":"'
    yield test, (RegexPattern(r'''//''\:""'''),
                 r'''/"'\:'''), r'''://''\:"":/"'\::'''
    yield test, (RegexPattern(r'''//''\:""'''),
                 r'''/"'\\:'''), r'''://''\:"":/"'\\\::''', False
    yield test, ("str", "abc"), Error("invalid value: regex=('str', 'abc')")
    yield test, ("str", 42), Error("invalid value: regex=('str', 42)")