def __init__(self, name, command, terminal_command, context):
        # Here we define this rule's spoken-form and special elements. Note that
        # nested_repetitions is the only one that contains Repetitions, and it
        # is not itself repeated. This is for performance purposes.
        spec = ("[<sequence>] "
                "[<nested_repetitions>] "
                "[<terminal_command>] "
                "[<final_command>]")
        extras = [
            Repetition(command, min=1, max=5, name="sequence"),
            Alternative([RuleRef(rule=character_rule)],
                        name="nested_repetitions"),
            ElementWrapper("terminal_command", terminal_command),
            RuleRef(rule=final_rule, name="final_command"),
        ]
        defaults = {
            "sequence": [],
            "nested_repetitions": None,
            "terminal_command": None,
            "final_command": None,
        }

        CompoundRule.__init__(self,
                              name=name,
                              spec=spec,
                              extras=extras,
                              defaults=defaults,
                              exported=True,
                              context=context)
예제 #2
0
class VimCommand(CompoundRule):
    spec = ('[<app>] [<literal>]')
    extras = [
        Repetition(Alternative([ruleCommand, RuleRef(Insertion())]),
                   max=10,
                   name='app'),
        RuleRef(LiteralIdentifierInsertion(), name='literal')
    ]

    def _process_recognition(self, node, extras):
        insertion_buffer = []
        commands = []
        if 'app' in extras:
            for chunk in extras['app']:
                commands.extend(chunk)
        if 'literal' in extras:
            commands.extend(extras['literal'])
        for command in commands:
            mode, command = command
            if mode == 'i':
                insertion_buffer.append(command)
            else:
                execute_insertion_buffer(insertion_buffer)
                insertion_buffer = []
                command.execute(extras)
        execute_insertion_buffer(insertion_buffer)
예제 #3
0
class KeepRule(RepeatRule):
    repeatables = CommonRepeatables() + [
        RuleRef(rule=KeepRepeatablesRule()),
        RuleRef(rule=SharedChromeRepeatablesRule()),
    ]
    finishers = CommonFinishers() + [
        # RuleRef(rule=KeepFinishersRule()),
        RuleRef(rule=SharedChromeFinishersRule()),
    ]
예제 #4
0
 def __init__(self, exported):
     extras = [
         Alternative(name="word",
                     children=[
                         RuleRef(AbbreviationRule(False)),
                         RuleRef(SpecialWordRule(False)),
                         Dictation()
                     ])
     ]
     CompoundRule.__init__(self,
                           name=get_unique_rule_name(),
                           extras=extras,
                           exported=exported)
예제 #5
0
class ActionRule(MappingRule):
    mapping = {
        # "[<n>] <verb> <motion>": Key("%(n)s, %(verb)s") + execute_rule('motion'),
        # "[<n>] <verb> <object>": Key("%(n)s, %(verb)s") + execute_rule('object'),
        # FIXME: `select` is screwy with countable motions -- the meaning is different
        # -> disabling for now while preserving object/motion count
        "<verb> <motion>":
        Key("%(verb)s") + execute_rule('motion'),
        "<verb> <object>":
        Key("%(verb)s") + execute_rule('object'),
        "[<n>] <simple_verb>":
        Key("%(n)s, %(simple_verb)s"),
        "[<n>] <verb> line":
        Key("%(n)s, %(verb)s:2"),

        # Special cases:
        # TODO: replace sequence <letter_sequence>
        "replace spell <letter_sequence>":
        Key("R") + execute_rule('letter_sequence') + Key("escape"),
        "[<n>] replace <letter>":
        Key("%(n)s, r, %(letter)s"),
        "record <letter>":
        Key("q, %(letter)s"),

        # TODO: Take "select" out of "verbChoice", define it fully here
        "select line":
        Key("V"),
        "select last":
        Key("g, v"),
        "visual other":
        Key("o"),  # switch to other end of visual selection
        "(visual | select) block":
        Key("c-v"),
        "duplicate line":
        Key("y, y, p"),
    }
    extras = [
        IntegerRef("n", 1, 10),
        verbChoice("verb"),
        simpleVerbChoice("simple_verb"),
        letterChoice("letter"),
        RuleRef(rule=motion.MotionRule(name="action_motion"), name="motion"),
        RuleRef(rule=object.ObjectRule(name="action_object"), name="object"),
        RuleRef(rule=LetterSequenceRule(name="action_letter_sequence"),
                name="letter_sequence")
    ]
    defaults = {
        "n": 1,
    }
예제 #6
0
    def __init__(
        self,
        name,
        options,
        alias=None,
        base_options=[],
    ):
        alias = alias or name
        self.base_options = base_options

        super(GitCommandRule, self).__init__(
            name=name,
            spec='[help] ({}) <options>'.format(alias),
            exported=False,
            extras=[
                Repetition(
                    name='options',
                    min=0,
                    max=10,
                    child=RuleRef(
                        MappingRule(
                            name=name + '_options',
                            mapping=options,
                            exported=False,
                        )),
                )
            ],
        )
예제 #7
0
 def __init__(self,
              vim_mode_switcher=None,
              non_transitions=None,
              transitions=None,
              name=None,
              exported=None):
     if vim_mode_switcher is not None:
         assert isinstance(vim_mode_switcher, VimGrammarSwitcher)
     self.switcher = vim_mode_switcher
     if non_transitions is None: non_transitions = self.non_transitions
     if transitions is None: transitions = self.transitions
     assert all([
         not isinstance(x, Rule) or not x.exported
         for x in non_transitions + transitions
     ])
     spec = '<transition_command> [<repeat_command>]'
     extras = [
         RuleRef(RepeatActionRule(RuleOrElemAlternative(non_transitions),
                                  exported=False),
                 name='repeat_command'),
         RuleOrElemAlternative(transitions, name='transition_command')
     ]
     super(TransitionThenRepeatRule, self).__init__(name=name,
                                                    spec=spec,
                                                    extras=extras,
                                                    exported=exported)
예제 #8
0
class MotionRule(MappingRule):
    exported = True
    mapping = {
        "[<n>] <motion>": Key("%(n)d, %(motion)s"),
        "<quick_search>": execute_rule('quick_search'),
        "<mark>": execute_rule('mark'),
        "go <uncountableMotion>": Key("%(uncountableMotion)s"),
    }
    extras = [
        IntegerRef("n", 1, 10),
        motionChoice("motion"),
        uncountableMotionChoice("uncountableMotion"),
        RuleRef(rule = QuickSearchRule(name = "motion_qsearch"), name = "quick_search"),
        RuleRef(rule = MarkMotionRule(name = "motion_mark"), name = "mark"),
    ]
    defaults = {
        "n": 1,
    }
예제 #9
0
    def __init__(self, mapping_rule):
        single = RuleRef(rule=mapping_rule)
        series = Repetition(single, min=1, max=16, name="series")

        compound_spec = "<series>"
        compound_extras = [series]
        CompoundRule.__init__(self,
                              spec=compound_spec,
                              extras=compound_extras,
                              exported=True)
예제 #10
0
    def __init__(self, mapping, extras=None, defaults=None):
        mapping_rule = MappingRule(mapping=mapping, extras=extras,
                                   defaults=defaults, exported=False)
        single = RuleRef(rule=mapping_rule)
        series = Repetition(single, min=1, max=16, name="series")

        compound_spec = "<series>"
        compound_extras = [series]
        CompoundRule.__init__(self, spec=compound_spec,
                              extras=compound_extras, exported=True)
예제 #11
0
    def create(*from_rules, max_repetitions=50):
        name = "CCR"
        rules = []
        for rule in from_rules:
            rules.append(RuleRef(rule=rule))
            name += "_" + rule.name
        single_action = Alternative(rules)
        sequence = Repetition(single_action, min=1, max=max_repetitions,
                              name="sequence")

        return CCRRule(name=name, spec=CCRRule.spec, extras=[sequence])
예제 #12
0
class SurroundRule(MappingRule):
    mapping = {
        # Adding surround (done separately for object and motion to avoid nesting both):
        "(Sir | wrap) <object> [in] <surround>": Key("y, s") + execute_rule('object') + Key("%(surround)s"),
        "(Sir | wrap) <motion> [in] <surround>": Key("y, s") + execute_rule('motion') + Key("%(surround)s"),
        "(Sir | wrap) now [in] <surround>": Key("S, %(surround)s"),

        # Changing and deleting surround:
        "(change Sir | strange) [from] <surround> [to] <surround_alt>": Key("c,s") + Key("%(surround)s") + Key("%(surround_alt)"),
        "(delete Sir | sleet) <surround>": Key("d,s") + Key("%(surround)s"),
    }
    extras = [
        surroundChoice('surround'),
        surroundChoice('surround_alt'),
        RuleRef(rule = motion.MotionRule(name = "surround_motion"), name = "motion"),
        RuleRef(rule = object.ObjectRule(name = "surround_object"), name = "object"),
    ]
    defaults = {
        'modifier': 'inner',
    }
예제 #13
0
 def install(self, grammar):
     exclusive_context = self.context
     for child in self.children:
         child.install(grammar)
         exclusive_context = combine_contexts(exclusive_context, ~child.context)
     if self.action_map:
         element = RuleRef(rule=create_rule(self.name + "KeystrokeRule",
                                                  self.action_map,
                                                  self.element_map))
     else:
         element = Empty()
     if self.terminal_action_map:
         terminal_element = RuleRef(
             rule=create_rule(self.name + "TerminalRule",
                                    self.terminal_action_map,
                                    self.element_map))
     else:
         terminal_element = Empty()
     grammar.add_rule(RepeatRule(self.name + "RepeatRule",
                                 element,
                                 terminal_element,
                                 exclusive_context))
예제 #14
0
파일: builder.py 프로젝트: codebold/hiccup
    def __init__(self, name, context, rules):
        self._name = name

        rule_refs = list()

        for rule_ in rules:
            rule_refs.append(RuleRef(rule=rule_))

        # max should not be greater than 7
        self.extras.append(
            Repetition(Alternative(rule_refs), min=1, max=6, name="sequence"))

        super(RepeatRule, self).__init__(context=context)
예제 #15
0
    def __init__(self):
        commands = git_commands.all_commands(GitCommandRuleBuilder)
        spec = '[<cancel>] git [<command_with_options>] [<enter>] [<cancel>]'

        super(GitRule, self).__init__(
            spec=spec,
            extras=[
                RuleRef(name='cancel',
                        rule=MappingRule(
                            name='cancel',
                            mapping={'cancel [last]': Key('c-c')},
                        )),
                Alternative(
                    name='command_with_options',
                    children=commands,
                ),
                RuleRef(name='enter',
                        rule=MappingRule(
                            name='enter',
                            mapping={'enter': Key('enter')},
                        )),
            ],
        )
예제 #16
0
class InsertModeStartRule(MappingRule):
    exported = True
    mapping = {
        "change <motion> [<text>]": Key("c") + execute_rule('motion') + Text('%(text)s'),
        "change <object> [<text>]": Key("c") + execute_rule('object') + Text('%(text)s'),
        "change line [<text>]": Key("c,c") + Text('%(text)s'),

        "insert [<text>]": Key("i") + Text('%(text)s'),
        "prepend [<text>]": Key("I") + Text('%(text)s'),
        "after [<text>]": Key("a") + Text('%(text)s'),
        "append [<text>]": Key("A") + Text('%(text)s'),
        "oh [<text>]": Key("o") + Text('%(text)s'),
        "bo [<text>]": Key("O") + Text('%(text)s'),

        "insert last [<text>]": Key("g, i") + Text('%(text)s'),
    }
    extras = [
        RuleRef(rule = motion.MotionRule(name = "insert_motion"), name = "motion"),
        RuleRef(rule = object.ObjectRule(name = "insert_object"), name = "object"),
        Dictation("text"),
    ]
    defaults = {
        "text": "",
    }
예제 #17
0
def makePrefixedCompoundRule(prefix, mappingRule):
    alts = []
    alts.append(RuleRef(rule=mappingRule()))
    singleAction = Alternative(alts)
    seq = Repetition(singleAction, min=1, max=16, name="mySequence")

    class PrefixCompoundRule(CompoundRule):
        spec = prefix + " <mySequence>"
        extras = [seq]
        defaults = {}

        def _process_recognition(self, node, extras):
            sequence = extras["mySequence"]
            for action in sequence:
                action.execute()
            release.execute()

    dynamicName = "Prefix" + prefix + "Rule"
    PrefixCompoundRule.__name__ = dynamicName
    PrefixCompoundRule.__qualname__ = dynamicName
    return PrefixCompoundRule
예제 #18
0
        self.cached = {}

    def __getitem__(self, length):
        if length not in self.cached:
            self.cached[length] = aenea.misc.DigitalInteger('count', 1, length)
        return self.cached[length]


ruleDigitalInteger = _DigitalIntegerFetcher()


class LetterMapping(MappingRule):
    mapping = aenea.misc.LETTERS


ruleLetterMapping = RuleRef(LetterMapping(), name='LetterMapping')


def execute_insertion_buffer(insertion_buffer):
    if not insertion_buffer:
        return

    if insertion_buffer[0][0] is not None:
        insertion_buffer[0][0].execute()
    else:
        pass
        #Key('a').execute()

    for insertion in insertion_buffer:
        insertion[1].execute()
예제 #19
0
        "go [<n>] right": Key("right:%(n)s"),
        "say <dictation>": Function(say_text),
        "<format_type> <dictation>": Function(format_text),
        "control <letter>": Key("c-%(letter)s"),
        "equals": Text(" = "),
    }

    extras = [
        letter_choice("letter"),
        formatting_choice("format_type"),
        IntegerRef("n", 1, 100),
        Dictation("dictation"),
    ]


letter = RuleRef(rule=LetterRule(), name='letter')

letter_sequence = Repetition(Alternative([letter]),
                             min=1,
                             max=12,
                             name="letter_sequence")


class LetterSequenceRule(CompoundRule):
    spec = "<letter_sequence>"
    extras = [letter_sequence]

    def _process_recognition(self, node, extras):
        letter_sequence = extras["letter_sequence"]
        for letter in letter_sequence:
            letter.execute()
예제 #20
0
class WinSelectorRule(CompoundRule):

    spec = config.lang.win_selector
    extras = [win_names_ref]
    exported = False

    def value(self, node):
        if node.has_child_with_name("win_names"):
            window = node.get_child_by_name("win_names").value()
            if not isinstance(window, Window):
                window = get_default_window(window)
            return window
        return Window.get_foreground()


win_selector = RuleRef(WinSelectorRule(), name="win_selector")


# ---------------------------------------------------------------------------
# Internal monitor selector rule and element.

class MonSelectorRule(CompoundRule):

    spec = config.lang.mon_selector
    extras = [mon_names_ref]
    exported = False

    def value(self, node):
        if node.has_child_with_name("mon_names"):
            return node.get_child_by_name("mon_names").value()
        return None
예제 #21
0
def build_rule(custom_symbol=Impossible()):

    symbol = Alternative([RuleRef(rule=SymbolRule()), custom_symbol],
                         name='symbol')

    letter = RuleRef(rule=LetterRule(), name='letter')

    symbol_sequence = Optional(Repetition(Alternative([letter, symbol]),
                                          min=1,
                                          max=32),
                               name='symbol_sequence')
    """
	symbol_sequence = Sequence([
		Optional(Repetition(
			Alternative([letter, symbol]),
			min=1, max=32
		)),
		Optional(fluid_insert)
	], name='symbol_sequence')
	"""

    spell_rule = MappingRule(
        name="letter mapping",
        mapping={
            "press <symbol_sequence>":
            Function(execute_symbol_sequence),
            "spell <symbol_sequence> <fluid_insert>":
            Function(start_insert) + Function(execute_symbol_sequence) +
            Function(lambda fluid_insert: execute(fluid_insert)) +
            Function(end_insert),
            "trailing <symbol_sequence> <fluid_insert>":
            Function(start_insert) +
            Function(execute_symbol_sequence, spaced=True) +
            Function(lambda fluid_insert: execute(fluid_insert)) +
            Function(end_insert),
            "separate <symbol_sequence> <fluid_insert>":
            Function(start_insert) +
            Function(execute_symbol_sequence, spaced=True) + Key("backspace") +
            Function(lambda fluid_insert: execute(fluid_insert)) +
            Function(end_insert),

            #		# TODO Figure out how to bundle this into the rule below via defaults
            #		#"<symbol>":
            #		#	Function(start_insert)
            #		#	  #+ Function(execute_symbol)
            #		#	  + Function(lambda symbol: symbol.execute())
            #		#	  + Function(end_insert),
            #
            "<symbol> <symbol_sequence> <fluid_insert>":
            Function(start_insert) + Function(lambda symbol: execute(symbol)) +
            Function(execute_symbol_sequence) +
            Function(lambda fluid_insert: execute(fluid_insert)) +
            Function(end_insert),
            "<fluid_insert>":
            Function(start_insert) +
            Function(lambda fluid_insert: execute(fluid_insert)) +
            Function(end_insert),
        },
        extras=[
            symbol_sequence,
            symbol,
            fluid_insert,
        ],
    )

    return spell_rule
# import pydevd_pycharm
# pydevd_pycharm.settrace('localhost', port=8282, stdoutToServer=True, stderrToServer=True)

from dragonfly import Alternative, Repetition, CompoundRule, RuleRef, Grammar
from supporting import utils

from ccr import editing_commands, text_formatting, scan_line, window_control


alternatives = [
    RuleRef(rule=editing_commands.MultiEditRule()),
    RuleRef(rule=text_formatting.FormatRule()),
    RuleRef(rule=scan_line.ScanLineRule()),
    RuleRef(rule=window_control.PlaceFractionRule()),
    RuleRef(rule=window_control.FocusWinRule()),
    RuleRef(rule=window_control.FocusTitleRule()),
    RuleRef(rule=window_control.TranslateRule()),
    RuleRef(rule=window_control.NudgeRule()),
    RuleRef(rule=window_control.ResizeRule()),
    RuleRef(rule=window_control.StretchRule()),
]

try:  # putstringcommands is not included in the pushed source, because it contains personal data.
    from ccr import putstringcommands

    if putstringcommands.PutStringCommandsRule:
        alternatives.append(RuleRef(rule=putstringcommands.PutStringCommandsRule()))
except (ImportError, NameError) as e:
    pass

single_action = Alternative(alternatives)
        "Robin [<n>]": Key("r:%(n)d"),
        "Soda [<n>]": Key("s:%(n)d"),
        "Tango [<n>]": Key("t:%(n)d"),
        "Usurp [<n>]": Key("u:%(n)d"),
        "Victor [<n>]": Key("v:%(n)d"),
        "Whiskey [<n>]": Key("w:%(n)d"),
        "X-ray [<n>]": Key("x:%(n)d"),
        "Yankee [<n>]": Key("y:%(n)d"),
        "Zulu [<n>]": Key("z:%(n)d"),
    }
    extras = [IntegerRef("n", 1, 100),]
    defaults = {"n": 1,}


alternatives = []
alternatives.append(RuleRef(rule=NewAlphabetRule()))

single_action = Alternative(alternatives)

sequence = Repetition(single_action, min=1, max=16, name="sequence")


class AlphabetChainRule(CompoundRule):
    spec = "<sequence>"
    extras = [
        sequence, # Sequence of actions defined above.
    ]

    #  - node -- root node of the recognition parse tree.
    #  - extras -- dict of the "extras" special elements:
    #     . extras["sequence"] gives the sequence of actions.
예제 #24
0
 def build(self):
     return RuleRef(
         name=self.data['name'],
         rule=GitCommandRule(**self.data),
     )
예제 #25
0
        IntegerRef("n", 1, 100),
        Dictation("text"),
        Dictation("text2"),
        Choice("char", specialCharMap),
        Choice("modifier1", modifierMap),
        Choice("modifier2", modifierMap),
        Choice("modifierSingle", singleModifierMap),
        Choice("pressKey", pressKeyMap),
    ]
    defaults = {
        "n": 1,
    }


alternatives = []
alternatives.append(RuleRef(rule=KeystrokeRule()))
single_action = Alternative(alternatives)

sequence = Repetition(single_action, min=1, max=16, name="sequence")


class RepeatRule(CompoundRule):
    # Here we define this rule's spoken-form and special elements.
    spec = "<sequence> [[[and] repeat [that]] <n> times]"
    extras = [
        sequence,  # Sequence of actions defined above.
        IntegerRef("n", 1, 100),  # Times to repeat the sequence.
    ]
    defaults = {
        "n": 1,  # Default repeat count.
    }
예제 #26
0
def build_grammar(context):
    grammar = Grammar("cpp", context=(context))
    #grammar.add_rule(keyword_rule)
    grammar.add_rule(fluid.build_rule(RuleRef(rule=keyword_rule)))
    return grammar
예제 #27
0
from dragonfly import RuleRef, Repetition, CompoundRule, Dictation, IntegerRef, Grammar, MappingRule, Key

from keystroke import KeystrokeRule
from letterRule import LetterRule
from windowss import WindowsKeyRule4

import shared

shared.letter = RuleRef(rule=LetterRule(), name='letter')
shared.keystroke = RuleRef(rule=KeystrokeRule(), name='keystroke')
shared.letter_sequence = Repetition(shared.letter,
                                    min=1,
                                    max=32,
                                    name='letter_sequence')

from repeatt import RepeatRule

# def executeLetter(letter):
#     letter.execute()
#
#
# def executeLetterSequence(letter_sequence):
#     for letter in letter_sequence:
#         letter.execute()

# ---------------------------------------------------------------------------
# NormalMode

# class IntellijEnabler(CompoundRule):
#     spec = "intelijey"
#     def _process_recognition(self, node, extras):
예제 #28
0
    RuleRef,
    Alternative,
    Repetition,
    CompoundRule,
)

# from natlink import setMicState

import keyboard_justin as keyboard
#import words
#import programs

release = Key("shift:up, ctrl:up, alt:up")

alternatives = []
alternatives.append(RuleRef(rule=keyboard.KeystrokeRule()))
"""
alternatives.append(RuleRef(rule=words.FormatRule()))
alternatives.append(RuleRef(rule=words.ReFormatRule()))
alternatives.append(RuleRef(rule=words.NopeFormatRule()))
alternatives.append(RuleRef(rule=programs.ProgramsRule()))
"""
root_action = Alternative(alternatives)

sequence = Repetition(root_action, min=1, max=16, name="sequence")


class RepeatRule(CompoundRule):
    # Here we define this rule's spoken-form and special elements.
    spec = "<sequence> [[[and] repeat [that]] <n> times]"
    extras = [
예제 #29
0
def build_grammar(context):
    grammar = Grammar("default", context=(context))
    #grammar.add_rule(keyword_rule)
    custom = RuleRef(rule=keyword_rule, name='custom')
    grammar.add_rule(build_rule())
    return grammar
예제 #30
0
def build_grammar(context):
    grammar = Grammar("python", context=(context))
    #grammar.add_rule(keyword_rule)
    #grammar.add_rule(special_rule)
    grammar.add_rule(fluid.build_rule(RuleRef(rule=keyword_rule)))
    return grammar