Example #1
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 #2
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 #3
0
def main(args=sys.argv[1:]):
    parser, args = parseargs(args)

    if args.debug:
        log.setLevel(logging.DEBUG)

    loop = asyncio.get_event_loop()
    grbl = SerialGrbl(args.device, args.baudrate, loop)

    registry = load_key_bindings_for_prompt()
    history = InMemoryHistory()

    app_loop = create_asyncio_eventloop(loop=loop)
    app = create_prompt_application(message='> ',
                                    history=history,
                                    key_bindings_registry=registry)
    cli = CommandLineInterface(application=app, eventloop=app_loop)

    for key, func in key_to_func.items():
        func = functools.partial(func, grbl=grbl, loop=loop)
        registry.add_binding(key, eager=True)(func)

    try:
        main_task = asyncio.ensure_future(main_coro(loop, grbl, cli))
        return loop.run_until_complete(main_task)
    except (EOFError, KeyboardInterrupt):
        main_task.cancel()
        return 1
    except serial.SerialException as error:
        log.fatal(error)
        return 1
Example #4
0
class KeyBindings(object):
	
	register = load_key_bindings_for_prompt()
	
	@register.add_binding(Keys.ControlE)
	def _(event):
		event.cli.run_in_terminal(os._exit(0))
	
	@register.add_binding(Keys.ControlC)
	def _(event):
		""" control c gets current working directory"""
		event.cli.current_buffer.insert_text(os.getcwd())
	
	@register.add_binding(Keys.ControlD)
	def _(event):
		"""control-D for change directory"""
		event.cli.current_buffer.insert_text("cdir")
	
	@register.add_binding(Keys.ControlH)
	def _(event):
		"""short cut to home"""
		event.cli.current_buffer.insert_text("h")
	
	@register.add_binding(Keys.ControlS)
	def _(event):
		"""short cut to sh"""
		event.cli.current_buffer.insert_text('sh')
 def __init__(self, completer=None, history=None, auto_suggest=None):
     self.completer = completer if completer else WordCompleter(
         get_all_tags())
     self.history = history if history else FileHistory(HISTORY_FILE)
     self.auto_suggest = auto_suggest if auto_suggest else AutoSuggestFromHistory(
     )
     self.registry = load_key_bindings_for_prompt()
 def _create_keybindings_registry(self):
     registry = load_key_bindings_for_prompt()
     for keystroke, callback in self.keybindings:
         @registry.add_binding(keystroke)
         def _(event):
             """
             We use ``run_in_terminal``, because that ensures that the prompt is
             hidden right before something gets printed and it's drawn again
             after it. (Otherwise this would destroy the output.)
             """
             event.cli.run_in_terminal(lambda: callback(None))
     return registry
def main():
    # We start with a `Registry` of default key bindings.
    registry = load_key_bindings_for_prompt()

    # Create the decorators to be used for registering text objects and
    # operators in this registry.
    operator = create_operator_decorator(registry)
    text_object = create_text_object_decorator(registry)

    # Create a custom operator.

    @operator('R')
    def _(event, text_object):
        " Custom operator that reverses text. "
        buff = event.current_buffer

        # Get relative start/end coordinates.
        start, end = text_object.operator_range(buff.document)
        start += buff.cursor_position
        end += buff.cursor_position

        text = buff.text[start:end]
        text = ''.join(reversed(text))

        event.cli.current_buffer.text = buff.text[:start] + text + buff.text[
            end:]

    # Create a text object.

    @text_object('A')
    def _(event):
        " A custom text object that involves everything. "
        # Note that a `TextObject` has coordinatens, relative to the cursor position.
        buff = event.current_buffer
        return TextObject(
            -buff.document.cursor_position,  # The start.
            len(buff.text) - buff.document.cursor_position)  # The end.

    # Read input.
    print('There is a custom text object "A" that applies to everything')
    print('and a custom operator "r" that reverses the text object.\n')

    print('Things that are possible:')
    print('-  Riw    - reverse inner word.')
    print('-  yA     - yank everything.')
    print('-  RA     - reverse everything.')

    text = prompt('> ',
                  default='hello world',
                  key_bindings_registry=registry,
                  editing_mode=EditingMode.VI)
    print('You said: %s' % text)
Example #8
0
    def ask_password(self):
        hidden = [True]  # Nonlocal
        registry = load_key_bindings_for_prompt()

        @registry.add_binding(Keys.ControlT)
        def _(event):
            hidden[0] = not hidden[0]

        print('Press Ctrl-T to toggle password visibility')

        return prompt('Password: ',
                      is_password=Condition(lambda cli: hidden[0]),
                      key_bindings_registry=registry)
Example #9
0
def main():
    hidden = [True]  # Nonlocal
    registry = load_key_bindings_for_prompt()

    @registry.add_binding(Keys.ControlT)
    def _(event):
        ' When ControlT has been pressed, toggle visibility. '
        hidden[0] = not hidden[0]

    print('Type Control-T to toggle password visible.')
    password = prompt('Password: '******'You said: %s' % password)
Example #10
0
def main():
    hidden = [True] # Nonlocal
    registry = load_key_bindings_for_prompt()

    @registry.add_binding(Keys.ControlT)
    def _(event):
        ' When ControlT has been pressed, toggle visibility. '
        hidden[0] = not hidden[0]


    print('Type Control-T to toggle password visible.')
    password = prompt('Password: '******'You said: %s' % password)
Example #11
0
def main():
    # We start with a `Registry` of default key bindings.
    registry = load_key_bindings_for_prompt()

    # Add our own key binding to the registry of the key bindings manager.
    @registry.add_binding(Keys.F4)
    def _(event):
        """
        When F4 has been pressed. Insert "hello world" as text.
        """
        event.cli.current_buffer.insert_text('hello world')

    @registry.add_binding('x', 'y')
    def _(event):
        """
        (Useless, but for demoing.)
        Typing 'xy' will insert 'z'.

        Note that when you type for instance 'xa', the insertion of 'x' is
        postponed until the 'a' is typed. because we don't know earlier whether
        or not a 'y' will follow. However, prompt-toolkit should already give
        some visual feedback of the typed character.
        """
        event.cli.current_buffer.insert_text('z')

    @registry.add_binding('a', 'b', 'c')
    def _(event):
        " Typing 'abc' should insert 'd'. "
        event.cli.current_buffer.insert_text('d')

    @registry.add_binding(Keys.ControlT)
    def _(event):
        """
        Print 'hello world' in the terminal when ControlT is pressed.

        We use ``run_in_terminal``, because that ensures that the prompt is
        hidden right before ``print_hello`` gets executed and it's drawn again
        after it. (Otherwise this would destroy the output.)
        """
        def print_hello():
            print('hello world')
        event.cli.run_in_terminal(print_hello)


    # Read input.
    print('Press F4 to insert "hello world", type "xy" to insert "z":')
    text = prompt('> ', key_bindings_registry=registry)
    print('You said: %s' % text)
Example #12
0
def main():
    # We start with a `Registry` of default key bindings.
    registry = load_key_bindings_for_prompt()

    # Add our own key binding to the registry of the key bindings manager.
    @registry.add_binding(Keys.F4)
    def _(event):
        """
        When F4 has been pressed. Insert "hello world" as text.
        """
        event.cli.current_buffer.insert_text('hello world')

    @registry.add_binding('x', 'y')
    def _(event):
        """
        (Useless, but for demoing.)
        Typing 'xy' will insert 'z'.

        Note that when you type for instance 'xa', the insertion of 'x' is
        postponed until the 'a' is typed. because we don't know earlier whether
        or not a 'y' will follow. However, prompt-toolkit should already give
        some visual feedback of the typed character.
        """
        event.cli.current_buffer.insert_text('z')

    @registry.add_binding('a', 'b', 'c')
    def _(event):
        " Typing 'abc' should insert 'd'. "
        event.cli.current_buffer.insert_text('d')

    @registry.add_binding(Keys.ControlT)
    def _(event):
        """
        Print 'hello world' in the terminal when ControlT is pressed.

        We use ``run_in_terminal``, because that ensures that the prompt is
        hidden right before ``print_hello`` gets executed and it's drawn again
        after it. (Otherwise this would destroy the output.)
        """
        def print_hello():
            print('hello world')
        event.cli.run_in_terminal(print_hello)


    # Read input.
    print('Press F4 to insert "hello world", type "xy" to insert "z":')
    text = prompt('> ', key_bindings_registry=registry)
    print('You said: %s' % text)
Example #13
0
def main():
    # We start with a `Registry` of default key bindings.
    registry = load_key_bindings_for_prompt()

    # Create the decorators to be used for registering text objects and
    # operators in this registry.
    operator = create_operator_decorator(registry)
    text_object = create_text_object_decorator(registry)

    # Create a custom operator.

    @operator('R')
    def _(event, text_object):
        " Custom operator that reverses text. "
        buff = event.current_buffer

        # Get relative start/end coordinates.
        start, end = text_object.operator_range(buff.document)
        start += buff.cursor_position
        end += buff.cursor_position

        text = buff.text[start:end]
        text = ''.join(reversed(text))

        event.cli.current_buffer.text = buff.text[:start] + text + buff.text[end:]

    # Create a text object.

    @text_object('A')
    def _(event):
        " A custom text object that involves everything. "
        # Note that a `TextObject` has coordinatens, relative to the cursor position.
        buff = event.current_buffer
        return TextObject(
                -buff.document.cursor_position,  # The start.
                len(buff.text) - buff.document.cursor_position)  # The end.

    # Read input.
    print('There is a custom text object "A" that applies to everything')
    print('and a custom operator "r" that reverses the text object.\n')

    print('Things that are possible:')
    print('-  Riw    - reverse inner word.')
    print('-  yA     - yank everything.')
    print('-  RA     - reverse everything.')

    text = prompt('> ', default='hello world', key_bindings_registry=registry, editing_mode=EditingMode.VI)
    print('You said: %s' % text)
Example #14
0
def main():
    # We start with a `Registry` that contains the default key bindings.
    registry = load_key_bindings_for_prompt()

    # We add a custom key binding to space.
    @registry.add_binding(' ')
    def _(event):
        """
        When space is pressed, we check the word before the cursor, and
        autocorrect that.
        """
        b = event.cli.current_buffer
        w = b.document.get_word_before_cursor()

        if w is not None:
            if w in corrections:
                b.delete_before_cursor(count=len(w))
                b.insert_text(corrections[w])

        b.insert_text(' ')

    # Read input.
    text = prompt('Say something: ', key_bindings_registry=registry)
    print('You said: %s' % text)
Example #15
0
def main():
    # We start with a `Registry` that contains the default key bindings.
    registry = load_key_bindings_for_prompt()

    # We add a custom key binding to space.
    @registry.add_binding(' ')
    def _(event):
        """
        When space is pressed, we check the word before the cursor, and
        autocorrect that.
        """
        b = event.cli.current_buffer
        w = b.document.get_word_before_cursor()

        if w is not None:
            if w in corrections:
                b.delete_before_cursor(count=len(w))
                b.insert_text(corrections[w])

        b.insert_text(' ')

    # Read input.
    text = prompt('Say something: ', key_bindings_registry=registry)
    print('You said: %s' % text)
    def __init__(self,
                 get_globals=None, get_locals=None, history_filename=None,
                 vi_mode=False,

                 # For internal use.
                 _completer=None, _validator=None,
                 _lexer=None, _extra_buffers=None, _extra_buffer_processors=None,
                 _on_start=None,
                 _extra_layout_body=None, _extra_toolbars=None,
                 _input_buffer_height=None,
                 _accept_action=AcceptAction.RETURN_DOCUMENT,
                 _on_exit=AbortAction.RAISE_EXCEPTION):

        self.get_globals = get_globals or (lambda: {})
        self.get_locals = get_locals or self.get_globals

        self._completer = _completer or PythonCompleter(self.get_globals, self.get_locals)
        self._validator = _validator or PythonValidator(self.get_compiler_flags)
        self.history = FileHistory(history_filename) if history_filename else InMemoryHistory()
        self._lexer = _lexer or PygmentsLexer(PythonLexer)
        self._extra_buffers = _extra_buffers
        self._accept_action = _accept_action
        self._on_exit = _on_exit
        self._on_start = _on_start

        self._input_buffer_height = _input_buffer_height
        self._extra_layout_body = _extra_layout_body or []
        self._extra_toolbars = _extra_toolbars or []
        self._extra_buffer_processors = _extra_buffer_processors or []

        # Settings.
        self.show_signature = False
        self.show_docstring = False
        self.show_meta_enter_message = True
        self.completion_visualisation = CompletionVisualisation.MULTI_COLUMN
        self.completion_menu_scroll_offset = 1

        self.show_line_numbers = False
        self.show_status_bar = True
        self.wrap_lines = True
        self.complete_while_typing = True
        self.vi_mode = vi_mode
        self.paste_mode = False  # When True, don't insert whitespace after newline.
        self.confirm_exit = True  # Ask for confirmation when Control-D is pressed.
        self.accept_input_on_enter = 2  # Accept when pressing Enter 'n' times.
                                        # 'None' means that meta-enter is always required.
        self.enable_open_in_editor = True
        self.enable_system_bindings = True
        self.enable_input_validation = True
        self.enable_auto_suggest = False
        self.enable_mouse_support = False
        self.enable_history_search = False  # When True, like readline, going
                                            # back in history will filter the
                                            # history on the records starting
                                            # with the current input.

        self.highlight_matching_parenthesis = False
        self.show_sidebar = False  # Currently show the sidebar.
        self.show_sidebar_help = True # When the sidebar is visible, also show the help text.
        self.show_exit_confirmation = False  # Currently show 'Do you really want to exit?'
        self.terminal_title = None  # The title to be displayed in the terminal. (None or string.)
        self.exit_message = 'Do you really want to exit?'
        self.insert_blank_line_after_output = True  # (For the REPL.)

        # Tokens to be shown at the prompt.
        self.prompt_style = 'classic'  # The currently active style.

        self.all_prompt_styles = {  # Styles selectable from the menu.
            'ipython': IPythonPrompt(self),
            'classic': ClassicPrompt(),
        }

        self.get_input_prompt_tokens = lambda cli: \
            self.all_prompt_styles[self.prompt_style].in_tokens(cli)

        self.get_output_prompt_tokens = lambda cli: \
            self.all_prompt_styles[self.prompt_style].out_tokens(cli)

        #: Load styles.
        self.code_styles = get_all_code_styles()
        self.ui_styles = get_all_ui_styles()
        self._current_code_style_name = 'default'
        self._current_ui_style_name = 'default'

        if is_windows():
            self._current_code_style_name = 'win32'

        self._current_style = self._generate_style()
        self.true_color = False

        # Options to be configurable from the sidebar.
        self.options = self._create_options()
        self.selected_option_index = 0

        #: Incremeting integer counting the current statement.
        self.current_statement_index = 1

        # Code signatures. (This is set asynchronously after a timeout.)
        self.signatures = []

        # Create a Registry for the key bindings.
        self.key_bindings_registry = MergedRegistry([
            ConditionalRegistry(
                registry=load_key_bindings_for_prompt(
                    enable_abort_and_exit_bindings=True,
                    enable_search=True,
                    enable_open_in_editor=Condition(lambda cli: self.enable_open_in_editor),
                    enable_system_bindings=Condition(lambda cli: self.enable_system_bindings),
                    enable_auto_suggest_bindings=Condition(lambda cli: self.enable_auto_suggest)),

                # Disable all default key bindings when the sidebar or the exit confirmation
                # are shown.
                filter=Condition(lambda cli: not (self.show_sidebar or self.show_exit_confirmation))
            ),
            load_mouse_bindings(),
            load_python_bindings(self),
            load_sidebar_bindings(self),
            load_confirm_exit_bindings(self),
        ])

        # Boolean indicating whether we have a signatures thread running.
        # (Never run more than one at the same time.)
        self._get_signatures_thread_running = False
Example #17
0
#!/usr/bin/env python

from __future__ import unicode_literals
import requests
from prompt_toolkit import prompt, AbortAction
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.contrib.completers import WordCompleter
from pygments.token import Token

from prompt_toolkit.key_binding.defaults import load_key_bindings_for_prompt
from prompt_toolkit.keys import Keys

from cheat_prompt.prompt_style import PromptStyle

registry = load_key_bindings_for_prompt()


def create_prompt(cli):
    """Create the prompt"""
    return [
        (Token.PromptText, 'Choose a cheatsheet '),
        (Token.PromptSymbol, '=> '),
    ]


def create_autocomplete_dictionary():
    """
    Create a dictionary for autocomplete from all the files in the path
    """
    data = requests.get("http://cheat.sh/:list").text
    completion_list = data.split()
Example #18
0
def create_prompt_application(layout,
                              buf=None,
                              buffers=None,
                              initial_focussed_buffer=DEFAULT_BUFFER,
                              default=None,
                              accept_filter=None,
                              validator=None,
                              history=None,
                              key_bindings_registry=None,
                              style=None,
                              mouse_support=False):
    assert validator is None or callable(validator) or isinstance(
        validator, Validator)
    assert style is None or isinstance(style, Mapping)

    _validator = validator
    if not (_validator is None or isinstance(_validator, Validator)):

        class _Validator(Validator):
            def validate(self, document):
                try:
                    message = validator(document.text)
                except ValidationError:
                    raise
                except Exception as ex:
                    raise ValidationError(message=ex.message,
                                          cursor_position=len(document.text))
                else:
                    if message is not True:
                        if message is False:
                            message = 'invalid input'
                        raise ValidationError(message=message,
                                              cursor_position=len(
                                                  document.text))

        _validator = _Validator()

    if key_bindings_registry is None:
        key_bindings_registry = load_key_bindings_for_prompt(
            enable_search=False,
            enable_auto_suggest_bindings=False,
            enable_system_bindings=True,
        )

    buf = buf or Buffer(
        accept_action=Acceptor(default, accept_filter),
        validator=_validator,
        history=history,
    )

    if style is not None:
        style = style_from_dict(style)

    return Application(
        layout=layout,
        buffer=buf,
        buffers=buffers,
        initial_focussed_buffer=initial_focussed_buffer,
        style=style or DEFAULT_STYLE,
        key_bindings_registry=key_bindings_registry,
        mouse_support=mouse_support,
    )
Example #19
0
    def __init__(
            self,
            get_globals=None,
            get_locals=None,
            history_filename=None,
            vi_mode=False,

            # For internal use.
            _completer=None,
            _validator=None,
            _lexer=None,
            _extra_buffers=None,
            _extra_buffer_processors=None,
            _on_start=None,
            _extra_layout_body=None,
            _extra_toolbars=None,
            _input_buffer_height=None,
            _accept_action=AcceptAction.RETURN_DOCUMENT,
            _on_exit=AbortAction.RAISE_EXCEPTION):

        self.get_globals = get_globals or (lambda: {})
        self.get_locals = get_locals or self.get_globals

        self._completer = _completer or PythonCompleter(
            self.get_globals, self.get_locals)
        self._validator = _validator or PythonValidator(
            self.get_compiler_flags)
        self.history = FileHistory(
            history_filename) if history_filename else InMemoryHistory()
        self._lexer = _lexer or PygmentsLexer(PythonLexer)
        self._extra_buffers = _extra_buffers
        self._accept_action = _accept_action
        self._on_exit = _on_exit
        self._on_start = _on_start

        self._input_buffer_height = _input_buffer_height
        self._extra_layout_body = _extra_layout_body or []
        self._extra_toolbars = _extra_toolbars or []
        self._extra_buffer_processors = _extra_buffer_processors or []

        # Settings.
        self.show_signature = False
        self.show_docstring = False
        self.show_meta_enter_message = True
        self.completion_visualisation = CompletionVisualisation.MULTI_COLUMN
        self.completion_menu_scroll_offset = 1

        self.show_line_numbers = False
        self.show_status_bar = True
        self.wrap_lines = True
        self.complete_while_typing = True
        self.vi_mode = vi_mode
        self.paste_mode = False  # When True, don't insert whitespace after newline.
        self.confirm_exit = True  # Ask for confirmation when Control-D is pressed.
        self.accept_input_on_enter = 2  # Accept when pressing Enter 'n' times.
        # 'None' means that meta-enter is always required.
        self.enable_open_in_editor = True
        self.enable_system_bindings = True
        self.enable_input_validation = True
        self.enable_auto_suggest = False
        self.enable_mouse_support = False
        self.enable_history_search = False  # When True, like readline, going
        # back in history will filter the
        # history on the records starting
        # with the current input.

        self.highlight_matching_parenthesis = False
        self.show_sidebar = False  # Currently show the sidebar.
        self.show_sidebar_help = True  # When the sidebar is visible, also show the help text.
        self.show_exit_confirmation = False  # Currently show 'Do you really want to exit?'
        self.terminal_title = None  # The title to be displayed in the terminal. (None or string.)
        self.exit_message = 'Do you really want to exit?'
        self.insert_blank_line_after_output = True  # (For the REPL.)

        # Tokens to be shown at the prompt.
        self.prompt_style = 'classic'  # The currently active style.

        self.all_prompt_styles = {  # Styles selectable from the menu.
            'ipython': IPythonPrompt(self),
            'classic': ClassicPrompt(),
        }

        self.get_input_prompt_tokens = lambda cli: \
            self.all_prompt_styles[self.prompt_style].in_tokens(cli)

        self.get_output_prompt_tokens = lambda cli: \
            self.all_prompt_styles[self.prompt_style].out_tokens(cli)

        #: Load styles.
        self.code_styles = get_all_code_styles()
        self.ui_styles = get_all_ui_styles()
        self._current_code_style_name = 'default'
        self._current_ui_style_name = 'default'

        if is_windows():
            self._current_code_style_name = 'win32'

        self._current_style = self._generate_style()
        self.true_color = False

        # Options to be configurable from the sidebar.
        self.options = self._create_options()
        self.selected_option_index = 0

        #: Incremeting integer counting the current statement.
        self.current_statement_index = 1

        # Code signatures. (This is set asynchronously after a timeout.)
        self.signatures = []

        # Create a Registry for the key bindings.
        self.key_bindings_registry = MergedRegistry([
            ConditionalRegistry(
                registry=load_key_bindings_for_prompt(
                    enable_abort_and_exit_bindings=True,
                    enable_search=True,
                    enable_open_in_editor=Condition(
                        lambda cli: self.enable_open_in_editor),
                    enable_system_bindings=Condition(
                        lambda cli: self.enable_system_bindings),
                    enable_auto_suggest_bindings=Condition(
                        lambda cli: self.enable_auto_suggest)),

                # Disable all default key bindings when the sidebar or the exit confirmation
                # are shown.
                filter=Condition(lambda cli: not (self.show_sidebar or self.
                                                  show_exit_confirmation))),
            load_mouse_bindings(),
            load_python_bindings(self),
            load_sidebar_bindings(self),
            load_confirm_exit_bindings(self),
        ])

        # Boolean indicating whether we have a signatures thread running.
        # (Never run more than one at the same time.)
        self._get_signatures_thread_running = False