Python prompt_toolkit.enums.DEFAULT_BUFFER Examples

The following are 18 code examples of prompt_toolkit.enums.DEFAULT_BUFFER(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module prompt_toolkit.enums , or try the search function .
Example #1
Source File: python_input.py    From ptpython with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _create_buffer(self) -> Buffer:
        """
        Create the `Buffer` for the Python input.
        """
        python_buffer = Buffer(
            name=DEFAULT_BUFFER,
            complete_while_typing=Condition(lambda: self.complete_while_typing),
            enable_history_search=Condition(lambda: self.enable_history_search),
            tempfile_suffix=".py",
            history=self.history,
            completer=ThreadedCompleter(self._completer),
            validator=ConditionalValidator(
                self._validator, Condition(lambda: self.enable_input_validation)
            ),
            auto_suggest=ConditionalAutoSuggest(
                ThreadedAutoSuggest(AutoSuggestFromHistory()),
                Condition(lambda: self.enable_auto_suggest),
            ),
            accept_handler=self._accept_handler,
            on_text_changed=self._on_input_timeout,
        )

        return python_buffer 
Example #2
Source File: basic.py    From android_universal with MIT License 6 votes vote down vote up
def load_abort_and_exit_bindings():
    """
    Basic bindings for abort (Ctrl-C) and exit (Ctrl-D).
    """
    registry = Registry()
    handle = registry.add_binding

    @handle(Keys.ControlC)
    def _(event):
        " Abort when Control-C has been pressed. "
        event.cli.abort()

    @Condition
    def ctrl_d_condition(cli):
        """ Ctrl-D binding is only active when the default buffer is selected
        and empty. """
        return (cli.current_buffer_name == DEFAULT_BUFFER and
                not cli.current_buffer.text)

    handle(Keys.ControlD, filter=ctrl_d_condition)(get_by_name('end-of-file'))

    return registry 
Example #3
Source File: repl.py    From crash with Apache License 2.0 6 votes vote down vote up
def create_buffer(cmd, history_file):
    def accept(buff):
        get_app().exit(result=buff.document.text)
        return True

    history = TruncatedFileHistory(history_file, max_length=MAX_HISTORY_LENGTH)
    completer = SQLCompleter(cmd)
    buffer = CrashBuffer(
        name=DEFAULT_BUFFER,
        history=history,
        completer=completer,
        enable_history_search=True,
        accept_handler=accept,
        on_text_insert=Capitalizer(cmd, completer).apply_capitalization,
        tempfile_suffix=lambda: '.sql'
    )
    buffer.complete_while_typing = lambda cli=None: cmd.should_autocomplete()
    return buffer 
Example #4
Source File: clibuffer.py    From athenacli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def cli_is_multiline(cli):
    @Condition
    def cond():
        doc = get_app().layout.get_buffer_by_name(DEFAULT_BUFFER).document
        if not cli.multi_line:
            return False
        else:
            return not _multiline_exception(doc.text)
    return cond 
Example #5
Source File: controls.py    From android_universal with MIT License 5 votes vote down vote up
def __init__(self,
                 buffer_name=DEFAULT_BUFFER,
                 input_processors=None,
                 lexer=None,
                 preview_search=False,
                 search_buffer_name=SEARCH_BUFFER,
                 get_search_state=None,
                 menu_position=None,
                 default_char=None,
                 focus_on_click=False):
        assert input_processors is None or all(isinstance(i, Processor) for i in input_processors)
        assert menu_position is None or callable(menu_position)
        assert lexer is None or isinstance(lexer, Lexer)
        assert get_search_state is None or callable(get_search_state)
        assert default_char is None or isinstance(default_char, Char)

        self.preview_search = to_cli_filter(preview_search)
        self.get_search_state = get_search_state
        self.focus_on_click = to_cli_filter(focus_on_click)

        self.input_processors = input_processors or []
        self.buffer_name = buffer_name
        self.menu_position = menu_position
        self.lexer = lexer or SimpleLexer()
        self.default_char = default_char or Char(token=Token.Transparent)
        self.search_buffer_name = search_buffer_name

        #: Cache for the lexer.
        #: Often, due to cursor movement, undo/redo and window resizing
        #: operations, it happens that a short time, the same document has to be
        #: lexed. This is a faily easy way to cache such an expensive operation.
        self._token_cache = SimpleCache(maxsize=8)

        self._xy_to_cursor_position = None
        self._last_click_timestamp = None
        self._last_get_processed_line = None 
Example #6
Source File: server.py    From android_universal with MIT License 5 votes vote down vote up
def _handle_command(self, command):
        """
        Handle command. This will run in a separate thread, in order not
        to block the event loop.
        """
        logger.info('Handle command %r', command)

        def in_executor():
            self.handling_command = True
            try:
                if self.callback is not None:
                    self.callback(self, command)
            finally:
                self.server.call_from_executor(done)

        def done():
            self.handling_command = False

            # Reset state and draw again. (If the connection is still open --
            # the application could have called TelnetConnection.close()
            if not self.closed:
                self.cli.reset()
                self.cli.buffers[DEFAULT_BUFFER].reset()
                self.cli.renderer.request_absolute_cursor_position()
                self.vt100_output.flush()
                self.cli._redraw()

        self.server.run_in_executor(in_executor) 
Example #7
Source File: mssqlbuffer.py    From mssql-cli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def mssql_is_multiline(mssql_cli):
    @Condition
    def cond():
        doc = get_app().layout.get_buffer_by_name(DEFAULT_BUFFER).document

        if not mssql_cli.multiline:
            return False
        if mssql_cli.multiline_mode == 'safe':
            return True
        return not _multiline_exception(doc.text)

    return cond 
Example #8
Source File: prompt.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _create_default_buffer(self) -> Buffer:
        """
        Create and return the default input buffer.
        """
        dyncond = self._dyncond

        # Create buffers list.
        def accept(buff: Buffer) -> bool:
            """ Accept the content of the default buffer. This is called when
            the validation succeeds. """
            cast(Application[str], get_app()).exit(result=buff.document.text)
            return True  # Keep text, we call 'reset' later on.

        return Buffer(
            name=DEFAULT_BUFFER,
            # Make sure that complete_while_typing is disabled when
            # enable_history_search is enabled. (First convert to Filter,
            # to avoid doing bitwise operations on bool objects.)
            complete_while_typing=Condition(
                lambda: is_true(self.complete_while_typing)
                and not is_true(self.enable_history_search)
                and not self.complete_style == CompleteStyle.READLINE_LIKE
            ),
            validate_while_typing=dyncond("validate_while_typing"),
            enable_history_search=dyncond("enable_history_search"),
            validator=DynamicValidator(lambda: self.validator),
            completer=DynamicCompleter(
                lambda: ThreadedCompleter(self.completer)
                if self.complete_in_thread and self.completer
                else self.completer
            ),
            history=self.history,
            auto_suggest=DynamicAutoSuggest(lambda: self.auto_suggest),
            accept_handler=accept,
            tempfile_suffix=lambda: to_str(self.tempfile_suffix or ""),
            tempfile=lambda: to_str(self.tempfile or ""),
        ) 
Example #9
Source File: layout.py    From azure-cli-shell with MIT License 5 votes vote down vote up
def create_tutorial_layout(lex):
    """ layout for example tutorial """
    lexer, _, _ = get_lexers(lex, None, None)
    layout_full = HSplit([
        FloatContainer(
            Window(
                BufferControl(
                    input_processors=input_processors,
                    lexer=lexer,
                    preview_search=Always()),
                get_height=get_height),
            [
                Float(xcursor=True,
                      ycursor=True,
                      content=CompletionsMenu(
                          max_height=MAX_COMPLETION,
                          scroll_offset=1,
                          extra_filter=(HasFocus(DEFAULT_BUFFER))))]),
        ConditionalContainer(
            HSplit([
                get_hline(),
                get_param(lexer),
                get_hline(),
                Window(
                    content=BufferControl(
                        buffer_name='example_line',
                        lexer=lexer
                    ),
                ),
                Window(
                    TokenListControl(
                        get_tutorial_tokens,
                        default_char=Char(' ', Token.Toolbar)),
                    height=D.exact(1)),
            ]),
            filter=~IsDone() & RendererHeightIsKnown()
        )
    ])
    return layout_full 
Example #10
Source File: app.py    From azure-cli-shell with MIT License 5 votes vote down vote up
def example_repl(self, text, example, start_index, continue_flag):
        """ REPL for interactive tutorials """

        if start_index:
            start_index = start_index + 1
            cmd = ' '.join(text.split()[:start_index])
            example_cli = CommandLineInterface(
                application=self.create_application(
                    full_layout=False),
                eventloop=create_eventloop())
            example_cli.buffers['example_line'].reset(
                initial_document=Document(u'{}\n'.format(
                    add_random_new_lines(example)))
            )
            while start_index < len(text.split()):
                if self.default_command:
                    cmd = cmd.replace(self.default_command + ' ', '')
                example_cli.buffers[DEFAULT_BUFFER].reset(
                    initial_document=Document(
                        u'{}'.format(cmd),
                        cursor_position=len(cmd)))
                example_cli.request_redraw()
                answer = example_cli.run()
                if not answer:
                    return "", True
                answer = answer.text
                if answer.strip('\n') == cmd.strip('\n'):
                    continue
                else:
                    if len(answer.split()) > 1:
                        start_index += 1
                        cmd += " " + answer.split()[-1] + " " +\
                               u' '.join(text.split()[start_index:start_index + 1])
            example_cli.exit()
            del example_cli
        else:
            cmd = text

        return cmd, continue_flag

    # pylint: disable=too-many-branches 
Example #11
Source File: app.py    From azure-cli-shell with MIT License 5 votes vote down vote up
def create_application(self, full_layout=True):
        """ makes the application object and the buffers """
        if full_layout:
            layout = create_layout(self.lexer, ExampleLexer, ToolbarLexer)
        else:
            layout = create_tutorial_layout(self.lexer)

        buffers = {
            DEFAULT_BUFFER: Buffer(is_multiline=True),
            'description': Buffer(is_multiline=True, read_only=True),
            'parameter' : Buffer(is_multiline=True, read_only=True),
            'examples' : Buffer(is_multiline=True, read_only=True),
            'bottom_toolbar' : Buffer(is_multiline=True),
            'example_line' : Buffer(is_multiline=True),
            'default_values' : Buffer(),
            'symbols' : Buffer()
        }

        writing_buffer = Buffer(
            history=self.history,
            auto_suggest=AutoSuggestFromHistory(),
            enable_history_search=True,
            completer=self.completer,
            complete_while_typing=Always()
        )

        return Application(
            mouse_support=False,
            style=self.styles,
            buffer=writing_buffer,
            on_input_timeout=self.on_input_timeout,
            key_bindings_registry=registry,
            layout=layout,
            buffers=buffers,
        ) 
Example #12
Source File: pgbuffer.py    From pgcli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def buffer_should_be_handled(pgcli):
    @Condition
    def cond():
        if not pgcli.multi_line:
            _logger.debug("Not in multi-line mode. Handle the buffer.")
            return True

        if pgcli.multiline_mode == "safe":
            _logger.debug("Multi-line mode is set to 'safe'. Do NOT handle the buffer.")
            return False

        doc = get_app().layout.get_buffer_by_name(DEFAULT_BUFFER).document
        text = doc.text.strip()

        return (
            text.startswith("\\")  # Special Command
            or text.endswith(r"\e")  # Special Command
            or text.endswith(r"\G")  # Ended with \e which should launch the editor
            or _is_complete(text)  # A complete SQL command
            or (text == "exit")  # Exit doesn't need semi-colon
            or (text == "quit")  # Quit doesn't need semi-colon
            or (text == ":q")  # To all the vim fans out there
            or (text == "")  # Just a plain enter without any text
        )

    return cond 
Example #13
Source File: clibuffer.py    From litecli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def cli_is_multiline(cli):
    @Condition
    def cond():
        doc = get_app().layout.get_buffer_by_name(DEFAULT_BUFFER).document

        if not cli.multi_line:
            return False
        else:
            return not _multiline_exception(doc.text)

    return cond 
Example #14
Source File: layout.py    From ptpython with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def meta_enter_message(python_input: "PythonInput") -> Container:
    """
    Create the `Layout` for the 'Meta+Enter` message.
    """

    def get_text_fragments() -> StyleAndTextTuples:
        return [("class:accept-message", " [Meta+Enter] Execute ")]

    @Condition
    def extra_condition() -> bool:
        " Only show when... "
        b = python_input.default_buffer

        return (
            python_input.show_meta_enter_message
            and (
                not b.document.is_cursor_at_the_end
                or python_input.accept_input_on_enter is None
            )
            and "\n" in b.text
        )

    visible = ~is_done & has_focus(DEFAULT_BUFFER) & extra_condition

    return ConditionalContainer(
        content=Window(FormattedTextControl(get_text_fragments)), filter=visible
    ) 
Example #15
Source File: __init__.py    From edgedb with Apache License 2.0 5 votes vote down vote up
def is_multiline() -> bool:
    doc = pt_app.get_app().layout.get_buffer_by_name(
        pt_enums.DEFAULT_BUFFER).document

    if (doc.cursor_position and doc.text[doc.cursor_position:].strip()):
        return True

    return is_multiline_text(doc.text) 
Example #16
Source File: main.py    From athenacli with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _build_prompt_app(self, history):
        key_bindings = cli_bindings(self)

        def get_message():
            prompt = self.get_prompt(self.prompt)
            if len(prompt) > self.MAX_LEN_PROMPT:
                prompt = self.get_prompt('\\r:\\d> ')
            return [('class:prompt', prompt)]

        def get_continuation(width, line_number, is_soft_wrap):
            continuation = ' ' * (width -1) + ' '
            return [('class:continuation', continuation)]

        def show_suggestion_tip():
            return self.iterations < 2

        get_toolbar_tokens = create_toolbar_tokens_func(
            self, show_suggestion_tip)

        with self._completer_lock:
            if self.key_bindings == 'vi':
                editing_mode = EditingMode.VI
            else:
                editing_mode = EditingMode.EMACS

            self.prompt_app = PromptSession(
                lexer=PygmentsLexer(Lexer),
                reserve_space_for_menu=self.get_reserved_space(),
                message=get_message,
                prompt_continuation=get_continuation,
                bottom_toolbar=get_toolbar_tokens,
                complete_style=CompleteStyle.COLUMN,
                input_processors=[ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars='[](){}'),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()
                )],
                tempfile_suffix='.sql',
                completer=DynamicCompleter(lambda: self.completer),
                history=history,
                auto_suggest=AutoSuggestFromHistory(),
                complete_while_typing=True,
                multiline=cli_is_multiline(self),
                style=style_factory(self.syntax_style, self.cli_style),
                include_default_pygments_style=False,
                key_bindings=key_bindings,
                enable_open_in_editor=True,
                enable_system_prompt=True,
                editing_mode=editing_mode,
                search_ignore_case=True
            ) 
Example #17
Source File: repl.py    From crash with Apache License 2.0 4 votes vote down vote up
def loop(cmd, history_file):
    buf = create_buffer(cmd, history_file)
    key_bindings = KeyBindings()
    bind_keys(buf, key_bindings)
    layout = create_layout(
        buffer=buf,
        multiline=True,
        lexer=PostgresLexer,
        extra_input_processors=[
            ConditionalProcessor(
                processor=HighlightMatchingBracketProcessor(chars='[](){}'),
                filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
        ],
        get_bottom_toolbar_tokens=lambda: get_toolbar_tokens(cmd),
        get_prompt_tokens=lambda: [('class:prompt', 'cr> ')]
    )
    output = get_default_output()
    app = Application(
        layout=layout,
        style=style_from_pygments_cls(CrateStyle),
        key_bindings=merge_key_bindings([
            key_bindings,
            load_open_in_editor_bindings()
        ]),
        editing_mode=_get_editing_mode(),
        output=output
    )
    cmd.get_num_columns = lambda: output.get_size().columns

    while True:
        try:
            text = app.run()
            if text:
                cmd.process(text)
            buf.reset()
        except ProgrammingError as e:
            if '401' in e.message:
                username = cmd.username
                password = cmd.password
                cmd.username = input('Username: ')
                cmd.password = getpass()
                try:
                    cmd.process(text)
                except ProgrammingError as ex:
                    # fallback to existing user/pw
                    cmd.username = username
                    cmd.password = password
                    cmd.logger.warn(str(ex))
            else:
                cmd.logger.warn(str(e))
        except KeyboardInterrupt:
            if isinstance(app.layout.current_control, SearchBufferControl):
                app.layout.current_control = app.layout.previous_control
            else:
                cmd.logger.warn("Query not cancelled. Run KILL <jobId> to cancel it")
                buf.reset()
        except EOFError:
            cmd.logger.warn('Bye!')
            return 
Example #18
Source File: history_browser.py    From ptpython with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def __init__(self, python_input, original_document):
        """
        Create an `Application` for the history screen.
        This has to be run as a sub application of `python_input`.

        When this application runs and returns, it retuns the selected lines.
        """
        self.python_input = python_input

        history_mapping = HistoryMapping(self, python_input.history, original_document)
        self.history_mapping = history_mapping

        document = Document(history_mapping.concatenated_history)
        document = Document(
            document.text,
            cursor_position=document.cursor_position
            + document.get_start_of_line_position(),
        )

        self.history_buffer = Buffer(
            document=document,
            on_cursor_position_changed=self._history_buffer_pos_changed,
            accept_handler=(
                lambda buff: get_app().exit(result=self.default_buffer.text)
            ),
            read_only=True,
        )

        self.default_buffer = Buffer(
            name=DEFAULT_BUFFER,
            document=history_mapping.get_new_document(),
            on_cursor_position_changed=self._default_buffer_pos_changed,
            read_only=True,
        )

        self.help_buffer = Buffer(document=Document(HELP_TEXT, 0), read_only=True)

        self.history_layout = HistoryLayout(self)

        self.app = Application(
            layout=self.history_layout.layout,
            full_screen=True,
            style=python_input._current_style,
            mouse_support=Condition(lambda: python_input.enable_mouse_support),
            key_bindings=create_key_bindings(self, python_input, history_mapping),
        )