Example #1
0
 def __init__(self):
     # prepare websocket client
     self.info_peer_count = 0
     self.info_last_event_time = False
     self.info_my_balance = False
     self.info_my_address = False
     self.block = False
     self.client_factory = ClientFactory(url='ws://127.0.0.1:{}'.format(Prisma().api.port))
     self.client_factory.prompt = self
     self.client_connection = connectWS(self.client_factory)
     # prompt style
     self.print_style_green = style_from_dict({
         Token.Text: '#00cc00',
     })
     self.print_style_red = style_from_dict({
         Token.Text: '#cc0000',
     })
     self.prompt_style = style_from_dict({
         Token.Pound:    '#ffff00',
         Token.Toolbar:  '#00ee00 bg:#333333',
     })
     # prompt autocompletion
     words = []
     for command in self.command_list:
         words.append(command['command'])
     self.completer = WordCompleter(words, ignore_case=True, sentence=True)
     # prompt memory
     self.history = FileHistory(expanduser('~/.prisma/history.txt'))
Example #2
0
def default_style():
    """ Default coloring """
    if platform.system() == 'Windows':
        styles = style_from_dict({
            # Completion colors
            Token.Menu.Completions.Completion.Current: 'bg:#7c2c80 #ffffff',
            Token.Menu.Completions.Completion: 'bg:#00b7b7 #ffffff',
            Token.Menu.Completions.ProgressButton: 'bg:#b78991',
            Token.Menu.Completions.ProgressBar: 'bg:#ffc0cb',

            Token.Az: '#7c2c80',
            Token.Prompt.Arg: '#888888',

            # Pretty Words
            Token.Keyword: '#965699',
            Token.Keyword.Declaration: '#ab77ad',
            Token.Name.Class: '#c49fc5',
            Token.Text: '#0f5050',

            Token.Line: '#E500E5',
            Token.Number: '#00ffff',
            # toolbar
            Token.Operator: 'bg:#000000 #ffffff',
            Token.Toolbar: 'bg:#000000 #ffffff'
        })

    else:
        styles = style_from_dict({
            # Completion colors
            Token.Menu.Completions.Completion.Current: 'bg:#7c2c80 #ffffff',
            Token.Menu.Completions.Completion: 'bg:#00b7b7 #ffffff',
            Token.Menu.Completions.ProgressButton: 'bg:#b78991',
            Token.Menu.Completions.ProgressBar: 'bg:#ffc0cb',

            Token.Az: '#7c2c80',
            Token.Prompt.Arg: '#888888',

            # Pretty Words
            Token.Keyword: '#965699',
            Token.Keyword.Declaration: '#ab77ad',
            Token.Name.Class: '#c49fc5',
            Token.Text: '#666666',

            Token.Line: '#E500E5',
            Token.Number: '#3d79db',
            # toolbar
            Token.Operator: 'bg:#000000 #ffffff',
            Token.Toolbar: 'bg:#000000 #ffffff'
        })

    return styles
Example #3
0
    def color(self):
        from pygments.token import Token
        from prompt_toolkit.shortcuts import prompt
        from prompt_toolkit.styles import style_from_dict

        example_style = style_from_dict({
            # User input.
            Token: '#ff0066',

            # Prompt.
            Token.Username: '******',
            Token.At: '#00aa00',
            Token.Colon: '#00aa00',
            Token.Pound: '#00aa00',
            Token.Host: '#000088 bg:#aaaaff',
            Token.Path: '#884444 underline',
        })

        def get_prompt_tokens(cli):
            return [
                (Token.Username, 'john'),
                (Token.At, '@'),
                (Token.Host, 'localhost'),
                (Token.Colon, ':'),
                (Token.Path, '/user/john'),
                (Token.Pound, '# '),
            ]

        text = prompt(get_prompt_tokens=get_prompt_tokens, style=example_style)
Example #4
0
def run():
    # Create a `Registry` that contains the default key bindings.
    registry = load_key_bindings_for_prompt()

    # Add an additional key binding for toggling this flag.
    @registry.add_binding(Keys.F4)
    def _(event):
        " Toggle between Emacs and Vi mode. "
        if event.cli.editing_mode == EditingMode.VI:
            event.cli.editing_mode = EditingMode.EMACS
        else:
            event.cli.editing_mode = EditingMode.VI

    # Add a bottom toolbar to display the status.
    style = style_from_dict({
        Token.Toolbar: 'reverse',
    })

    def get_bottom_toolbar_tokens(cli):
        " Display the current input mode. "
        text = 'Vi' if cli.editing_mode == EditingMode.VI else 'Emacs'
        return [
            (Token.Toolbar, ' [F4] %s ' % text)
        ]

    prompt('> ', key_bindings_registry=registry,
           get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
           style=style)
def run():
    vi_mode_enabled = False

    # Create a set of key bindings that have Vi mode enabled if the
    # ``vi_mode_enabled`` is True..
    manager = KeyBindingManager.for_prompt(
        enable_vi_mode=Condition(lambda cli: vi_mode_enabled))

    # Add an additional key binding for toggling this flag.
    @manager.registry.add_binding(Keys.F4)
    def _(event):
        " Toggle between Emacs and Vi mode. "
        nonlocal vi_mode_enabled
        vi_mode_enabled = not vi_mode_enabled

    # Add a bottom toolbar to display the status.
    style = style_from_dict({
        Token.Toolbar: 'reverse',
    })

    def get_bottom_toolbar_tokens(cli):
        " Display the current input mode. "
        text = 'Vi' if vi_mode_enabled else 'Emacs'
        return [
            (Token.Toolbar, ' [F4] %s ' % text)
        ]

    prompt('> ', key_bindings_registry=manager.registry,
           get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
           style=style)
Example #6
0
def get_style(theme):
    try:
        style = get_style_by_name(theme)
    except ClassNotFound:
        style = get_style_by_name('native')

        # Create styles dictionary.
    styles = {}
    styles.update(style.styles)
    styles.update(default_style_extensions)
    styles.update({
        Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
        Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
        Token.Scrollbar: 'bg:#00aaaa',
        Token.Scrollbar.Button: 'bg:#003333',
        Token.Toolbar: 'bg:#222222 #cccccc',
        Token.Toolbar.Off: 'bg:#222222 #696969',
        Token.Toolbar.On: 'bg:#222222 #ffffff',
        Token.Toolbar.Search: 'noinherit bold',
        Token.Toolbar.Search.Text: 'nobold',
        Token.Toolbar.System: 'noinherit bold',
        Token.Toolbar.Arg: 'noinherit bold',
        Token.Toolbar.Arg.Text: 'nobold',
        Token.Method: 'bg:#222222 #dddddd',
        Token.Url: 'bg:#222222 #dddddd noinherit italic',
        Token.Headers: 'bg:#222222 #999999'
    })
    return style_from_dict(styles)
Example #7
0
    def _init_style(self) -> dict:
        """
            Grab the values for the prompt styling.

            :return:
        """

        style = pygments.styles.get_style_by_name('vim')

        styles = {}
        styles.update(style.styles)
        styles.update(default_style_extensions)

        styles.update({
            # completions
            Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
            Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
            Token.Menu.Completions.ProgressButton: 'bg:#003333',
            Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',

            # User input.
            Token: '#ff0066',

            # Prompt.
            Token.Devicename: '#ff0000',
            Token.On: '#00aa00',
            Token.Devicetype: '#00ff48',
            Token.Version: '#00ff48',
            Token.Connection: '#717171'
        })

        return style_from_dict(styles)
Example #8
0
def style_factory(name, cli_style):
    """Get a named style for the CLI.

    Paramters
    ---------
    name: `str`
        Name of style class.
    cli_style: `dict`
    
    Returns
    -------
    pymgents.style.BaseStyle
    """
    try:
        style = pygments.styles.get_style_by_name(name)
    except ClassNotFound:
        style = pygments.styles.get_style_by_name('native')

    styles = {}
    styles.update(style.styles)
    styles.update(default_style_extensions)
    custom_styles = {string_to_tokentype(x): y for x, y in cli_style.items()}
    styles.update(custom_styles)

    return style_from_dict(styles)
Example #9
0
def run():
    # Create a `Registry` that contains the default key bindings.
    registry = load_key_bindings_for_prompt()

    # Add an additional key binding for toggling this flag.
    @registry.add_binding(Keys.F4)
    def _(event):
        " Toggle between Emacs and Vi mode. "
        if event.cli.editing_mode == EditingMode.VI:
            event.cli.editing_mode = EditingMode.EMACS
        else:
            event.cli.editing_mode = EditingMode.VI

    # Add a bottom toolbar to display the status.
    style = style_from_dict({
        Token.Toolbar: 'reverse',
    })

    def get_bottom_toolbar_tokens(cli):
        " Display the current input mode. "
        text = 'Vi' if cli.editing_mode == EditingMode.VI else 'Emacs'
        return [(Token.Toolbar, ' [F4] %s ' % text)]

    prompt('> ',
           key_bindings_registry=registry,
           get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
           style=style)
Example #10
0
def run():
    vi_mode_enabled = False

    # Create a set of key bindings that have Vi mode enabled if the
    # ``vi_mode_enabled`` is True..
    manager = KeyBindingManager.for_prompt(
        enable_vi_mode=Condition(lambda cli: vi_mode_enabled))

    # Add an additional key binding for toggling this flag.
    @manager.registry.add_binding(Keys.F4)
    def _(event):
        " Toggle between Emacs and Vi mode. "
        nonlocal vi_mode_enabled
        vi_mode_enabled = not vi_mode_enabled

    # Add a bottom toolbar to display the status.
    style = style_from_dict({
        Token.Toolbar: 'reverse',
    })

    def get_bottom_toolbar_tokens(cli):
        " Display the current input mode. "
        text = 'Vi' if vi_mode_enabled else 'Emacs'
        return [(Token.Toolbar, ' [F4] %s ' % text)]

    prompt('> ',
           key_bindings_registry=manager.registry,
           get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
           style=style)
def run():
    # Create a set of key bindings that have Vi mode enabled if the
    # ``vi_mode_enabled`` is True..
    manager = KeyBindingManager.for_prompt()

    # Add an additional key binding for toggling this flag.
    @manager.registry.add_binding(Keys.F4)
    def _(event):
        " Toggle between Emacs and Vi mode. "
        if event.cli.editing_mode == EditingMode.VI:
            event.cli.editing_mode = EditingMode.EMACS
        else:
            event.cli.editing_mode = EditingMode.VI

    # Add a bottom toolbar to display the status.
    style = style_from_dict({
        Token.Toolbar: 'reverse',
    })

    def get_bottom_toolbar_tokens(cli):
        " Display the current input mode. "
        text = 'Vi' if cli.editing_mode == EditingMode.VI else 'Emacs'
        return [(Token.Toolbar, ' [F4] %s ' % text)]

    prompt('> ',
           key_bindings_registry=manager.registry,
           get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
           style=style)
Example #12
0
    def __init__(self, configpath=''):
        # load existing configuration files if exists:
        if not configpath:
            configpath = os.path.join(os.path.expanduser('~'), '.poiconfig.json')
        if not os.path.exists(configpath):
            print('poi: configuration file does not exist. Please run poi-config first.')
            sys.exit(0)

        with open(configpath) as f:
            config = json.load(f)
        for key, value in config.items():
            setattr(self, key, value)

        self.color_style = style_from_dict({
            Token.Title: self.color['title'],
            Token.Link: self.color['link'],
            Token.HL1: self.color['highlight'][0],
            Token.HL2: self.color['highlight'][1],
            Token.HL3: self.color['highlight'][2],
            Token.Tag: self.color['tag'],
            Token.Text: '#ffffff roman',
            })

        self.notes = os.path.join(self.root, 'notes')
        self.refs = os.path.join(self.root, 'refs')
        self.backups = os.path.join(self.root, '.backups')

        self.history = []
        self.link_listing = []
        self.last_notepath = ''

        self.index = PoiIndex(os.path.join(self.root, '.index.txt'), os.path.join(self.notes, '*' + self.file_ext))
        self.tag_index = TagIndex(os.path.join(self.root, '.tag_index.txt'), os.path.join(self.notes, '*' + self.file_ext))
Example #13
0
def color_mapping(curr_completion, completion, prompt, command, subcommand,
                  param, text, line, example, toolbar):

    return style_from_dict({
        # Completion colors
        Token.Menu.Completions.Completion.Current: curr_completion,
        Token.Menu.Completions.Completion: completion,
        Token.Menu.Completions.ProgressButton: 'bg:#b78991',
        Token.Menu.Completions.ProgressBar: 'bg:#ffc0cb',

        Token.Az: prompt,
        Token.Prompt.Arg: prompt,

        # Pretty Words
        Token.Keyword: command,
        Token.Keyword.Declaration: subcommand,
        Token.Name.Class: param,
        Token.Text: text,

        Token.Line: line,
        Token.Number: example,
        # toolbar
        Token.Operator: toolbar,
        Token.Toolbar: toolbar
    })
Example #14
0
def color_mapping(curr_completion, completion, prompt, command, subcommand,
                  param, text, line, example, toolbar):

    return style_from_dict({
        # Completion colors
        Token.Menu.Completions.Completion.Current: curr_completion,
        Token.Menu.Completions.Completion: completion,
        Token.Menu.Completions.ProgressButton: 'bg:#b78991',
        Token.Menu.Completions.ProgressBar: 'bg:#ffc0cb',

        Token.Az: prompt,
        Token.Prompt.Arg: prompt,

        # Pretty Words
        Token.Keyword: command,
        Token.Keyword.Declaration: subcommand,
        Token.Name.Class: param,
        Token.Text: text,

        Token.Line: line,
        Token.Number: example,
        # toolbar
        Token.Operator: toolbar,
        Token.Toolbar: toolbar
    })
Example #15
0
    def __init__(self,
                 walletpath,
                 walletpass,
                 operation,
                 params=None,
                 deploy=False):
        self.start_height = Blockchain.Default().Height
        self.start_dt = datetime.datetime.utcnow()
        self.walletpath = walletpath
        self.walletpass = walletpass
        self.Wallet = None
        self.operation = operation
        self.neo_fund_sc = ''
        self.neo_fund_sc_addr = ''
        self.contract_script = None
        self.params = params
        self.go_on = True
        self._walletdb_loop = None
        self.deploy = deploy
        self._known_addresses = []
        self.contract_addr = None
        self.history = FileHistory('.prompt.py.history')

        self.token_style = style_from_dict({
            Token.Command:
            settings.token_style['Command'],
            Token.Neo:
            settings.token_style['Neo'],
            Token.Default:
            settings.token_style['Default'],
            Token.Number:
            settings.token_style['Number'],
        })
def run():
    # Create a set of key bindings that have Vi mode enabled if the
    # ``vi_mode_enabled`` is True..
    manager = KeyBindingManager.for_prompt()

    # Add an additional key binding for toggling this flag.
    @manager.registry.add_binding(Keys.F4)
    def _(event):
        " Toggle between Emacs and Vi mode. "
        if event.cli.editing_mode == EditingMode.VI:
            event.cli.editing_mode = EditingMode.EMACS
        else:
            event.cli.editing_mode = EditingMode.VI

    # Add a bottom toolbar to display the status.
    style = style_from_dict({
        Token.Toolbar: 'reverse',
    })

    def get_bottom_toolbar_tokens(cli):
        " Display the current input mode. "
        text = 'Vi' if cli.editing_mode == EditingMode.VI else 'Emacs'
        return [
            (Token.Toolbar, ' [F4] %s ' % text)
        ]

    prompt('> ', key_bindings_registry=manager.registry,
           get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
           style=style)
Example #17
0
    def test_style_inheritance(self):
        style = style_from_dict({
            Token: '#ff0000',
            Token.A.B.C: 'bold',
            Token.A.B.C.D: '#ansired',
            Token.A.B.C.D.E: 'noinherit blink'
        })

        expected = Attrs(color='ff0000',
                         bgcolor=None,
                         bold=True,
                         underline=False,
                         italic=False,
                         blink=False,
                         reverse=False)
        self.assertEqual(style.get_attrs_for_token(Token.A.B.C), expected)

        expected = Attrs(color='ansired',
                         bgcolor=None,
                         bold=True,
                         underline=False,
                         italic=False,
                         blink=False,
                         reverse=False)
        self.assertEqual(style.get_attrs_for_token(Token.A.B.C.D), expected)

        expected = Attrs(color=None,
                         bgcolor=None,
                         bold=False,
                         underline=False,
                         italic=False,
                         blink=True,
                         reverse=False)
        self.assertEqual(style.get_attrs_for_token(Token.A.B.C.D.E), expected)
Example #18
0
    def __init__(self, style):
        """Initialize the style given the name."""
        base_module = _load_style('default')
        module = _load_style(style)

        self._style = style_from_dict(ChainMap(module.style, base_module.style))
        self._token_to_attrs_dict = None
        self._templates = ChainMap(module.templates, base_module.templates)
Example #19
0
    def _get_style(self):

        return style_from_dict({
            Token.Selected: '#FF9D00',
            Token.Instruction: '',
            Token.Answer: '#FF9D00 bold',
            Token.Question: 'bold'
        })
Example #20
0
    def __init__(self):

        self.switch = {
            'help': help,
            #'list': list,
            'load': load,
            'newpackage': newpackage,
            'clonepackage': clonepackage,
            'use': use,
            'info': info,
            'select': select,
            'deselect': deselect,
            'exit': exit,
            'quit': exit,
            'tparam': tparam,
            'newtest': newtest,
            'clonetest': clonetest,
            'save': save,
            'testlist': testlist,
            'importfile': importfile,
            'go': go,
            'deletefile': deletefile,
            'deletetest': deletetest,
            'deleteconfig': deleteconfig,
            'tedit': tedit,
            'newconfig': newconfig,
            'rparam': rparam,
            'cparam': cparam,
            'tconfig': tconfig,
            'nodelist': nodelist,
            'tfiles': tfiles,
            'nodespower': nodespower,
            'updatenodes': updatenodes,
            'pingnodes': pingnodes,
        }
        self.environ = {
            "config": configparser.ConfigParser(),
        }
        self.context = {"package": TestPackage()}

        self.environ['config'].read(CONF_PATH)

        self.sorted = contextSorter(self.switch)

        #Colors of prompt terminal
        self.style = style_from_dict({
            Token: '#ff0066',
            #dotmarks token
            Token.Colon: '#fefefe',
            #Test token
            Token.At: '#00ff00',
            #Config token
            Token.Pound: '#ff00ff',
            #Package token
            Token.Username: '******',
        })
Example #21
0
    def __init__(self):
        self.start_height = Blockchain.Default().Height
        self.start_dt = datetime.datetime.utcnow()

        self.token_style = style_from_dict({
            Token.Command: preferences.token_style['Command'],
            Token.Neo: preferences.token_style['Neo'],
            Token.Default: preferences.token_style['Default'],
            Token.Number: preferences.token_style['Number'],
        })
Example #22
0
    def _get_style(self):

        return style_from_dict(
            {
                Token.Selected: '#08e3ff',
                Token.Instruction: '#ff2408',
                Token.Answer: '#08e3ff bold',
                Token.Question: '#fff bold'
            }
        )
Example #23
0
    def __init__(self):
        self.input_parser = InputParser()
        self.start_height = Blockchain.Default().Height
        self.start_dt = datetime.datetime.utcnow()

        self.token_style = style_from_dict({
            Token.Command: preferences.token_style['Command'],
            Token.Neo: preferences.token_style['Neo'],
            Token.Default: preferences.token_style['Default'],
            Token.Number: preferences.token_style['Number'],
        })
Example #24
0
class ToolBar(object):

    toolBarStyle = style_from_dict({
        Token.Toolbar: '#gggggg bg:#444444',
    })

    def get_bottom_toolbar_tokens(self, cli):
        return [(
            Token.Toolbar,
            "Control-E [Exit] Control-S [SH] Control-T [tod] Control-A [shows all commands]"
        )]
Example #25
0
    def do(self, comm):
        from prompt_toolkit.shortcuts import print_tokens
        from prompt_toolkit.styles import style_from_dict
        from pygments.token import Token

        print_tokens([
            (Token, "\n\t"),
            (Token.Msg, self.text),
            (Token, "\n"),
        ],
                     style=style_from_dict({Token.Msg: 'reverse'}))
Example #26
0
def main():
    style = style_from_dict({
        Token.Hello: '#ff0066',
        Token.World: '#44ff44 italic',
    })
    tokens = [
        (Token.Hello, 'Hello '),
        (Token.World, 'World'),
        (Token, '\n'),
    ]
    print_tokens(tokens, style=style)
Example #27
0
def shell():
    c = Chitin()

    cmd_history = FileHistory(os.path.expanduser('~') + '/.chitin.history')
    print(WELCOME)
    message = VERSION

    def get_bottom_toolbar_tokens(cli):
        return [(Token.Toolbar, ' ' + message)]

    style = style_from_dict({
        Token.Toolbar: '#ffffff bg:#333333',
    })
    completer = SystemCompleter()
    del completer.completers["executable"]

    # Check whether files in and around the current directory have been changed...
    for failed in util.check_integrity_set(set(".")):
        print("[WARN] '%s' has been modified outside of lab book." % failed)
    try:
        while True:
            cmd_str = ""
            while len(cmd_str.strip()) == 0:
                cmd_str = prompt(
                    u'===> ',
                    history=cmd_history,
                    auto_suggest=AutoSuggestFromHistory(),
                    completer=completer,
                    lexer=PygmentsLexer(BashLexer),
                    get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
                    style=style,
                    on_abort=AbortAction.RETRY,
                )

            fields = cmd_str.split(" ")
            command_set = [" ".join(fields)]

            skip, special_command_set = c.attempt_special(cmd_str)
            if skip:
                continue
            if len(special_command_set) > 0:
                command_set = special_command_set

            #####################################
            handled = c.super_handle(command_set)
            if handled:
                if "message" in handled:
                    message = handled["message"]
                else:
                    message = VERSION
            #####################################

    except EOFError:
        print("Bye!")
Example #28
0
    def run(tasks):
        """
        Performs list of tasks.

        Each task is defined as list: [<telecommand object>, Send|SendReceive, "Wait|NoWait"]

        When using "Wait" it is necessary to type 'n<ENTER>' to continue running tasks
        """
        import pprint
        from prompt_toolkit.shortcuts import print_tokens
        from prompt_toolkit.styles import style_from_dict
        from pygments.token import Token

        style = style_from_dict({
            Token.Timestamp: '#fdf6e3',
            Token.CurrentStep: '#b58900',
            Token.TotalSteps: '#6c71c4',
            Token.Action: '#dc322f',
            Token.Telecommand: '#268bd2',
        })

        step_no = 0

        for [telecommand, action_type, wait] in tasks:
            step_no += 1

            tokens = [
                (Token.String, "["),
                (Token.Timestamp,
                 datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f')),
                (Token.String, "] "), (Token.String, "Step "),
                (Token.CurrentStep, str(step_no)), (Token.String, "/"),
                (Token.TotalSteps, str(len(tasks))), (Token.String, ": "),
                (Token.Action, action_type.__name__), (Token.String, "("),
                (Token.Telecommand, pprint.pformat(telecommand)),
                (Token.String, ")... ")
            ]

            print_tokens(tokens, style=style)

            action_type(telecommand).do(__import__(__name__))

            if wait is "NoWait":
                print_tokens([(Token.String, "Done"), (Token.String, "\n")],
                             style=style)
            else:
                print_tokens(
                    [(Token.String, "Wait (type 'n' and press <Enter>)")],
                    style=style)

                user = ""
                while user[:1] != "n":
                    user = raw_input()
Example #29
0
    def __prompt_init(self):
        self.asm_history = InMemoryHistory()
        self.dsm_history = InMemoryHistory()

        self.prompt_style = style_from_dict({
            Token: '#ff0066',
            Token.OS: '#ff3838',
            Token.Colon: '#ffffff',
            Token.Mode: '#f9a9c3 bold',
            Token.Arch: '#5db2fc',
            Token.Pound: '#ffd82a',
        })
Example #30
0
def test_with_style():
    f = _Capture()
    style = style_from_dict({
        Token.Hello: '#ff0066',
        Token.World: '#44ff44 italic',
    })
    tokens = [
        (Token.Hello, 'Hello '),
        (Token.World, 'world'),
    ]
    print_tokens(tokens, style=style, file=f)
    assert b'\x1b[0;38;5;197mHello' in f.data
    assert b'\x1b[0;38;5;83;3mworld' in f.data
 def __init__(self, title='Interactive Shell', add_help=True):
     self.title = title
     self.style = style_from_dict({
         Token.Toolbar: '#ffffff bg:#333333',
     })
     if add_help:
         self.commands['help'] = dict(
             help = 'Show this help message',
         )
     self.history = InMemoryHistory()
     self.completer = WordCompleter(sorted(self.commands.keys()))
     self.parser = self._create_parser()
     self.registry = self._create_keybindings_registry()
Example #32
0
def test_style_from_dict():
    style = style_from_dict({
        Token.A: '#ff0000 bold underline italic',
        Token.B: 'bg:#00ff00 blink reverse',
    })

    expected = Attrs(color='ff0000', bgcolor=None, bold=True,
                     underline=True, italic=True, blink=False, reverse=False)
    assert style.get_attrs_for_token(Token.A) == expected

    expected = Attrs(color=None, bgcolor='00ff00', bold=False,
                     underline=False, italic=False, blink=True, reverse=True)
    assert style.get_attrs_for_token(Token.B) == expected
Example #33
0
def notice_print(message):

    notice_style = style_from_dict({
        Token.Notice: '#44ff44 bold',
        Token.Message: '#000000 italic',
    })

    tokens = [
        (Token.Notice, 'Notice: '),
        (Token.Message, message),
        (Token, '\n'),
    ]
    print_tokens(tokens, style=notice_style)
Example #34
0
def warning_print(message):

    warning_style = style_from_dict({
        Token.Warning: '#d3ac2b bold',
        Token.Message: '#000000 italic',
    })

    tokens = [
        (Token.Warning, 'Warning: '),
        (Token.Message, message),
        (Token, '\n'),
    ]
    print_tokens(tokens, style=warning_style)
Example #35
0
def error_print(message):

    error_style = style_from_dict({
        Token.Error: '#ff0066 bold',
        Token.Message: '#000000 italic',
    })

    tokens = [
        (Token.Error, 'Error: '),
        (Token.Message, message),
        (Token, '\n'),
    ]
    print_tokens(tokens, style=error_style)
def test_with_style():
    f = _Capture()
    style = style_from_dict({
        Token.Hello: '#ff0066',
        Token.World: '#44ff44 italic',
    })
    tokens = [
        (Token.Hello, 'Hello '),
        (Token.World, 'world'),
    ]
    print_tokens(tokens, style=style, file=f)
    assert b'\x1b[0;38;5;197mHello' in f.data
    assert b'\x1b[0;38;5;83;3mworld' in f.data
Example #37
0
def style_factory(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name)
    except ClassNotFound:
        style = pygments.styles.get_style_by_name('native')

    styles = {}
    styles.update(style.styles)
    styles.update(default_style_extensions)
    custom_styles = {string_to_tokentype(x): y for x, y in cli_style.items()}
    styles.update(custom_styles)

    return style_from_dict(styles)
Example #38
0
def style_factory(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name)
    except ClassNotFound:
        style = pygments.styles.get_style_by_name('native')

    styles = {}
    styles.update(style.styles)
    styles.update(default_style_extensions)
    custom_styles = dict([(string_to_tokentype(x), y) for x, y in cli_style.items()])
    styles.update(custom_styles)

    return style_from_dict(styles)
Example #39
0
def generate_style(python_style, ui_style):
    """
    Generate Pygments Style class from two dictionaries
    containing style rules.
    """
    assert isinstance(python_style, dict)
    assert isinstance(ui_style, dict)

    styles = {}
    styles.update(default_style_extensions)
    styles.update(python_style)
    styles.update(ui_style)

    return style_from_dict(styles)
Example #40
0
def get_editor_style_by_name(name):
    """
    Get Style class.
    This raises `pygments.util.ClassNotFound` when there is no style with this
    name.
    """
    style_cls = get_style_by_name(name)

    styles = {}
    styles.update(style_cls.styles)
    styles.update(DEFAULT_STYLE_EXTENSIONS)
    styles.update(style_extensions)

    return style_from_dict(styles)
Example #41
0
def generate_style(python_style, ui_style):
    """
    Generate Pygments Style class from two dictionaries
    containing style rules.
    """
    assert isinstance(python_style, dict)
    assert isinstance(ui_style, dict)

    styles = {}
    styles.update(DEFAULT_STYLE_EXTENSIONS)
    styles.update(python_style)
    styles.update(ui_style)

    return style_from_dict(styles)
Example #42
0
 def print_color(self, string, end='\n', **kwargs):
     """Prints a color string using prompt-toolkit color management."""
     if isinstance(string, str):
         tokens = partial_color_tokenize(string + end)
     else:
         # assume this is a list of (Token, str) tuples and just print
         tokens = string
     if HAS_PYGMENTS:
         env = builtins.__xonsh_env__
         self.styler.style_name = env.get('XONSH_COLOR_STYLE')
         proxy_style = PygmentsStyle(pyghooks.xonsh_style_proxy(self.styler))
     else:
         proxy_style = style_from_dict(DEFAULT_STYLE_DICT)
     print_tokens(tokens, style=proxy_style)
Example #43
0
 def print_colored(text):
     my_style = style_from_dict(Console.Colors)
     tokens = []
     while True:
         pos_start, size, token = Console.find_color(text)
         if pos_start != -1:
             text = text[pos_start+size:]
             pos_end, size, token_end = Console.find_color(text); token_end
             if pos_end != -1:
                 tokens.append((token, text[:pos_end]))
             else:
                 tokens.append((token, text))
                 break
         else:
             break       
     print_tokens(tokens, style=my_style)
Example #44
0
def test_style_inheritance():
    style = style_from_dict({
        Token: '#ff0000',
        Token.A.B.C: 'bold',
        Token.A.B.C.D: '#ansired',
        Token.A.B.C.D.E: 'noinherit blink'
    })

    expected = Attrs(color='ff0000', bgcolor=None, bold=True,
                     underline=False, italic=False, blink=False, reverse=False)
    assert style.get_attrs_for_token(Token.A.B.C) == expected

    expected = Attrs(color='ansired', bgcolor=None, bold=True,
                     underline=False, italic=False, blink=False, reverse=False)
    assert style.get_attrs_for_token(Token.A.B.C.D) == expected

    expected = Attrs(color=None, bgcolor=None, bold=False,
                     underline=False, italic=False, blink=True, reverse=False)
    assert style.get_attrs_for_token(Token.A.B.C.D.E) == expected
Example #45
0
    def style_factory(self, style_name):
        """Retrieve the specified pygments style.

        If the specified style is not found, the vim style is returned.

        :type style_name: str
        :param style_name: The pygments style name.

        :rtype: :class:`pygments.style.StyleMeta`
        :return: Pygments style info.
        """
        try:
            style = get_style_by_name(style_name)
        except ClassNotFound:
            style = get_style_by_name('vim')

        # Create a style dictionary.
        styles = {}
        styles.update(style.styles)
        styles.update(default_style_extensions)
        t = Token
        styles.update({
            t.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
            t.Menu.Completions.Completion: 'bg:#008888 #ffffff',
            t.Menu.Completions.Meta.Current: 'bg:#00aaaa #000000',
            t.Menu.Completions.Meta: 'bg:#00aaaa #ffffff',
            t.Scrollbar.Button: 'bg:#003333',
            t.Scrollbar: 'bg:#00aaaa',
            t.Toolbar: 'bg:#222222 #cccccc',
            t.Toolbar.Off: 'bg:#222222 #696969',
            t.Toolbar.On: 'bg:#222222 #ffffff',
            t.Toolbar.Search: 'noinherit bold',
            t.Toolbar.Search.Text: 'nobold',
            t.Toolbar.System: 'noinherit bold',
            t.Toolbar.Arg: 'noinherit bold',
            t.Toolbar.Arg.Text: 'nobold'
        })

        return style_from_dict(styles)
Example #46
0
    def style_factory(self, name):
        """Retrieves the specified pygments style.

        If the specified style is not found, the native style is returned.

        Args:
            * name: A string representing the pygments style.

        Returns:
            An instance of CliStyle.
        """
        try:
            style = pygments.styles.get_style_by_name(name)
        except ClassNotFound:
            style = pygments.styles.get_style_by_name('native')

        # Create styles dictionary.
        styles = {}
        styles.update(style.styles)
        styles.update(default_style_extensions)
        styles.update({
            Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
            Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
            Token.Scrollbar: 'bg:#00aaaa',
            Token.Scrollbar.Button: 'bg:#003333',
            Token.Toolbar: 'bg:#222222 #cccccc',
            Token.Toolbar.Off: 'bg:#222222 #696969',
            Token.Toolbar.On: 'bg:#222222 #ffffff',
            Token.Toolbar.Search: 'noinherit bold',
            Token.Toolbar.Search.Text: 'nobold',
            Token.Toolbar.System: 'noinherit bold',
            Token.Toolbar.Arg: 'noinherit bold',
            Token.Toolbar.Arg.Text: 'nobold'
        })

        return style_from_dict(styles)
Example #47
0
from __future__ import absolute_import, unicode_literals
import getpass
import os
from prompt_toolkit import prompt, AbortAction
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.token import Token
from prompt_toolkit.styles import style_from_dict
from prompt_toolkit.contrib.completers import WordCompleter


style = style_from_dict({
    Token.Username:  '******',
    Token.At:        '#999999',
    Token.Host:      '#81b71a',
    Token.Separator: '#81b71a',
    Token.Text:      '#e6e6e6',
    Token.Arrow:     '#999999',
    Token.SelectedText: 'reverse underline',
    Token.Toolbar: '#e6e6e6 bg:#262626',
})

history = FileHistory('.pytify-search-history')


def completer():
    list = []

    for name in history:
        list.append(name)

    return WordCompleter(set(list), ignore_case=True)
Example #48
0
try:
    curses.setupterm()
    nb_colors = curses.tigetnum("colors")
except Exception:
    nb_colors = 256

if nb_colors == 8:
    default = style_from_dict({
        Token.Path: 'bold #00ff00',
        Token.Pound: 'bold',
        Token.At: 'bold',
        Token.Host: '#0000ff',
        Token.Username: '******',

        Token.Menu.Completions.Completion: 'bg:#ffffff #000000',
        Token.Menu.Completions.Completion.Current: 'bold bg:#000000 #ffffff',
        Token.Menu.Completions.Meta: 'bg:#ffffff #000000',
        Token.Menu.Completions.Meta.Current: 'bold bg:#000000 #ffffff',
        Token.Menu.Completions.MultiColumnMeta: 'bg:#000000 #ffffff',
        Token.Menu.Completions.ProgressBar: 'bg:#ffffff',
        Token.Menu.Completions.ProgressButton: 'bg:#000000',
    })
else:
    default = style_from_dict({
        Token.Path: 'bold #009AC7',
        Token.Pound: 'bold #FFFFFF',
        Token.At: 'bold #dadada',
        Token.Host: '#ffaf00',
        Token.Username: '******',
Example #49
0
    if os.path.exists(dst) or os.path.islink(dst):
        os.unlink(dst)
    os.symlink(src, dst)


def _get_dirs(target_dir):
    if not os.path.isdir(target_dir):
        _echo(cformat('%{red}Directory not found:%{red!} {}').format(target_dir))
        sys.exit(1)
    return get_root_path('indico'), os.path.abspath(target_dir)


PROMPT_TOOLKIT_STYLE = style_from_dict({
    Token.HELP: '#aaaaaa',
    Token.PROMPT: '#5f87ff',
    Token.DEFAULT: '#dfafff',
    Token.BRACKET: '#ffffff',
    Token.COLON: '#ffffff',
    Token.INPUT: '#aaffaa',
})


def _prompt(message, default='', path=False, list_=None, required=True, validate=None, allow_invalid=False,
            password=False, help=None):
    def _get_prompt_tokens(cli):
        rv = [
            (Token.PROMPT, message),
            (Token.COLON, ': '),
        ]
        if first and help:
            rv.insert(0, (Token.HELP, wrap_text(help) + '\n'))
        return rv
Example #50
0
from __future__ import unicode_literals
from os import linesep
from axelrod import Actions, Player, init_args
from prompt_toolkit import prompt
from prompt_toolkit.token import Token
from prompt_toolkit.styles import style_from_dict
from prompt_toolkit.validation import Validator, ValidationError

C, D = Actions.C, Actions.D

toolbar_style = style_from_dict({
    Token.Toolbar: '#ffffff bg:#333333',
})


class ActionValidator(Validator):
    """
    A class to validate input from prompt_toolkit.prompt
    Described at http://python-prompt-toolkit.readthedocs.io/en/latest/pages/building_prompts.html#input-validation
    """

    def validate(self, document):
        text = document.text

        if text and text.upper() not in ['C', 'D']:
            raise ValidationError(
                message='Action must be C or D',
                cursor_position=0)


class Human(Player):
Example #51
0
from prompt_toolkit import prompt
from prompt_toolkit.styles import style_from_dict
from prompt_toolkit.token import Token
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.contrib.completers import WordCompleter
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.key_binding.manager import KeyBindingManager
from ui import get_bottom_toolbar_tokens

from command import command_parser

style = style_from_dict({
    Token.Toolbar: '#ffffff bg:#333333',
    Token.Red: '#ff0066',
    Token.Green: '#44ff44',
    Token.Orange: '#ff9900',
    Token.White: '#ffffff',
})

history = InMemoryHistory()
manager = KeyBindingManager.for_prompt()

toolbar_tokens =  lambda _: [
    (Token.Toolbar, ' '),
    (Token.Green, ' GRID ONLINE ')
]
#get_bottom_toolbar_tokens(p)

def grid_prompt(text='> '):
    return prompt(
Example #52
0
def get_md_styles():
    test_style = style_from_dict({
        Token.Toolbar: '#ffffff bg:#333333',
    })
    return test_style
Example #53
0
File: shell.py Project: jerluc/3R4
from prompt_toolkit.history import InMemoryHistory
from pygments.lexers.shell import BashLexer

from era.commands import PATH, expandvars
from era.env import Env
from era.fs import FS


SHELL_PATH = '/bin/esh'

# TODO: Read this from a config file
DEFAULT_PROMPT_STYLE = style_from_dict({
    # User input
    Token:            '#ffffff',
    # Prompt
    Token.Username:   '******',
    Token.Path:       '#2200cc',
    # Toolbar
    Token.Toolbar: '#ffffff bg:#333333',
})

ADMIN_PROMPT_STYLE = style_from_dict({
    # User input
    Token:            '#ffffff',
    # Prompt
    Token.Username:   '******',
    Token.Path:       '#2200cc',
    # Toolbar
    Token.Toolbar: '#ffffff bg:#333333',
})
Example #54
0
#!/usr/bin/env python
"""
Example of a right prompt. This is an additional prompt that is displayed on
the right side of the terminal. It will be hidden automatically when the input
is long enough to cover the right side of the terminal.

This is similar to RPROMPT is Zsh.
"""
from __future__ import unicode_literals

from prompt_toolkit import prompt
from prompt_toolkit.styles import style_from_dict
from prompt_toolkit.token import Token

example_style = style_from_dict({
    Token.RPrompt: 'bg:#ff0066 #ffffff',
})


def get_rprompt_tokens(cli):
    return [
        (Token, ' '),
        (Token.RPrompt, '<rprompt>'),
    ]


if __name__ == '__main__':
    answer = prompt('> ', get_rprompt_tokens=get_rprompt_tokens, style=example_style)
    print('You said: %s' % answer)
Example #55
0
 def __init__(self):
     self.ui_style = style_from_dict(ui_style)
     self._token_to_attrs_dict = None
"""
from __future__ import unicode_literals

from prompt_toolkit import prompt
from prompt_toolkit.styles import style_from_dict
from prompt_toolkit.token import Token


example_style = style_from_dict({
    # User input.
    Token:          '#ff0066',

    # Prompt.
    Token.Username: '******',
    Token.At:       '#00aa00',
    Token.Colon:    '#00aa00',
    Token.Pound:    '#00aa00',
    Token.Host:     '#000088 bg:#aaaaff',
    Token.Path:     '#884444 underline',

    # Make a selection reverse/underlined.
    # (Use Control-Space to select.)
    Token.SelectedText: 'reverse underline',
})


def get_prompt_tokens(cli):
    return [
        (Token.Username, 'john'),
        (Token.At,       '@'),
        (Token.Host,     'localhost'),
        (Token.Colon,    ':'),

operators1 = ['add', 'sub', 'div', 'mul']
operators2 = ['sqrt', 'log', 'sin', 'ln']


def create_grammar():
    return compile("""
        (\s*  (?P<operator1>[a-z]+)   \s+   (?P<var1>[0-9.]+)   \s+   (?P<var2>[0-9.]+)   \s*) |
        (\s*  (?P<operator2>[a-z]+)   \s+   (?P<var1>[0-9.]+)   \s*)
    """)


example_style = style_from_dict({
    Token.Operator:       '#33aa33 bold',
    Token.Number:         '#aa3333 bold',

    Token.TrailingInput: 'bg:#662222 #ffffff',
})


if __name__ == '__main__':
    g = create_grammar()

    lexer = GrammarLexer(g, lexers={
        'operator1': SimpleLexer(Token.Operator),
        'operator2': SimpleLexer(Token.Operator),
        'var1': SimpleLexer(Token.Number),
        'var2': SimpleLexer(Token.Number),
    })

    completer = GrammarCompleter(g, {
operators1 = ["add", "sub", "div", "mul"]
operators2 = ["sqrt", "log", "sin", "ln"]


def create_grammar():
    return compile(
        """
        (\s*  (?P<operator1>[a-z]+)   \s+   (?P<var1>[0-9.]+)   \s+   (?P<var2>[0-9.]+)   \s*) |
        (\s*  (?P<operator2>[a-z]+)   \s+   (?P<var1>[0-9.]+)   \s*)
    """
    )


example_style = style_from_dict(
    {Token.Operator: "#33aa33 bold", Token.Number: "#aa3333 bold", Token.TrailingInput: "bg:#662222 #ffffff"}
)


if __name__ == "__main__":
    g = create_grammar()

    lexer = GrammarLexer(
        g,
        lexers={
            "operator1": SimpleLexer(Token.Operator),
            "operator2": SimpleLexer(Token.Operator),
            "var1": SimpleLexer(Token.Number),
            "var2": SimpleLexer(Token.Number),
        },
    )