Пример #1
0
    def open_file(self, filename):
        """
        Open this file.
        """
        lexer = PygmentsLexer.from_filename(filename, sync_from_start=False)

        try:
            source = FileSource(filename, lexer=lexer)
        except IOError as e:
            self.message = '{}'.format(e)
        else:
            self.add_source(source)
Пример #2
0
    def lex_document(self, document):
        """
        Call the lexer and return a get_tokens_for_line function.
        """
        location = self.editor_buffer.location

        if location:
            if self.editor_buffer.in_file_explorer_mode:
                return PygmentsLexer(DirectoryListingLexer, sync_from_start=False).lex_document(document)

            return PygmentsLexer.from_filename(location, sync_from_start=False).lex_document(document)

        return SimpleLexer().lex_document(document)
Пример #3
0
def run():
    if is_windows():
        from prompt_toolkit.eventloop.win32 import Win32EventLoop
        loop = Win32EventLoop()
    else:
        from prompt_toolkit.eventloop.posix import PosixEventLoop
        from prompt_toolkit.eventloop.select import SelectSelector
        loop = PosixEventLoop(selector=SelectSelector)
    set_event_loop(loop)

    if not sys.stdin.isatty():
        pager = Pager.from_pipe()
        pager.run()
    else:
        parser = argparse.ArgumentParser(description='Browse through a text file.')
        parser.add_argument('filename', metavar='filename', nargs='+',
                            help='The file to be displayed.')
        parser.add_argument('--vi', help='Prefer Vi key bindings.', action='store_true')
        parser.add_argument('--emacs', help='Prefer Emacs key bindings.', action='store_true')

        args = parser.parse_args()

        # Determine input mode.
        vi_mode = 'vi' in os.environ.get('EDITOR', '').lower()
        if args.vi: vi_mode = True
        if args.emacs: vi_mode = False

        pager = Pager(vi_mode=vi_mode)

        # Open files.
        for filename in args.filename:
            # When a filename is given, take a lexer from that filename.
            lexer = PygmentsLexer.from_filename(filename, sync_from_start=False)

            pager.add_source(FileSource(filename, lexer=lexer))

        # Run UI.
        pager.run()
Пример #4
0
    def __init__(
            self,
            get_globals=None,
            get_locals=None,
            history_filename=None,
            vi_mode=False,
            input=None,
            output=None,
            color_depth=None,

            # For internal use.
            extra_key_bindings=None,
            _completer=None,
            _validator=None,
            _lexer=None,
            _extra_buffer_processors=None,
            _extra_layout_body=None,
            _extra_toolbars=None,
            _input_buffer_height=None):

        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._lexer = _lexer or PygmentsLexer(PythonLexer)

        if history_filename:
            self.history = ThreadedHistory(FileHistory(history_filename))
        else:
            self.history = InMemoryHistory()

        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 []

        self.extra_key_bindings = extra_key_bindings or KeyBindings()

        # 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.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.enable_syntax_highlighting = True
        self.swap_light_and_dark = False
        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.)

        # The buffers.
        self.default_buffer = self._create_buffer()
        self.search_buffer = Buffer()
        self.docstring_buffer = Buffer(read_only=True)

        # 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 = lambda: \
            self.all_prompt_styles[self.prompt_style].in_prompt()

        self.get_output_prompt = lambda: \
            self.all_prompt_styles[self.prompt_style].out_prompt()

        #: 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.color_depth = color_depth or ColorDepth.default()

        self.max_brightness = 1.0
        self.min_brightness = 0.0

        # 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 = []

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

        self.output = output or create_output()
        self.input = input or create_input(sys.stdin)

        self.style_transformation = merge_style_transformations([
            ConditionalStyleTransformation(
                SwapLightAndDarkStyleTransformation(),
                filter=Condition(lambda: self.swap_light_and_dark)),
            AdjustBrightnessStyleTransformation(lambda: self.min_brightness,
                                                lambda: self.max_brightness),
        ])
        self.ptpython_layout = PtPythonLayout(
            self,
            lexer=DynamicLexer(lambda: self._lexer if self.
                               enable_syntax_highlighting else SimpleLexer()),
            input_buffer_height=self._input_buffer_height,
            extra_buffer_processors=self._extra_buffer_processors,
            extra_body=self._extra_layout_body,
            extra_toolbars=self._extra_toolbars)

        self.app = self._create_application()

        if vi_mode:
            self.app.editing_mode = EditingMode.VI
Пример #5
0
Файл: lexer.py Проект: pg83/zm
 def __init__(self, python_lexer: Optional[Lexer] = None) -> None:
     self.python_lexer = python_lexer or PygmentsLexer(PythonLexer)
     self.system_lexer = PygmentsLexer(BashLexer)
Пример #6
0
    def _build_cli(self, history):
        key_bindings = pgcli_bindings(self)

        def get_message():
            if self.dsn_alias and self.prompt_dsn_format is not None:
                prompt_format = self.prompt_dsn_format
            else:
                prompt_format = self.prompt_format

            prompt = self.get_prompt(prompt_format)

            if (
                prompt_format == self.default_prompt
                and len(prompt) > self.max_len_prompt
            ):
                prompt = self.get_prompt("\\d> ")

            prompt = prompt.replace("\\x1b", "\x1b")
            return ANSI(prompt)

        def get_continuation(width, line_number, is_soft_wrap):
            continuation = self.multiline_continuation_char * (width - 1) + " "
            return [("class:continuation", continuation)]

        get_toolbar_tokens = create_toolbar_tokens_func(self)

        if self.wider_completion_menu:
            complete_style = CompleteStyle.MULTI_COLUMN
        else:
            complete_style = CompleteStyle.COLUMN

        with self._completer_lock:
            prompt_app = PromptSession(
                lexer=PygmentsLexer(PostgresLexer),
                reserve_space_for_menu=self.min_num_menu_lines,
                message=get_message,
                prompt_continuation=get_continuation,
                bottom_toolbar=get_toolbar_tokens,
                complete_style=complete_style,
                input_processors=[
                    # Highlight matching brackets while editing.
                    ConditionalProcessor(
                        processor=HighlightMatchingBracketProcessor(chars="[](){}"),
                        filter=HasFocus(DEFAULT_BUFFER) & ~IsDone(),
                    ),
                    # Render \t as 4 spaces instead of "^I"
                    TabsProcessor(char1=" ", char2=" "),
                ],
                auto_suggest=AutoSuggestFromHistory(),
                tempfile_suffix=".sql",
                # N.b. pgcli's multi-line mode controls submit-on-Enter (which
                # overrides the default behaviour of prompt_toolkit) and is
                # distinct from prompt_toolkit's multiline mode here, which
                # controls layout/display of the prompt/buffer
                multiline=True,
                history=history,
                completer=ThreadedCompleter(DynamicCompleter(lambda: self.completer)),
                complete_while_typing=True,
                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,
                enable_suspend=True,
                editing_mode=EditingMode.VI if self.vi_mode else EditingMode.EMACS,
                search_ignore_case=True,
            )

            return prompt_app
Пример #7
0
import asyncio
from typing import Dict, List, Any, Optional

from prompt_toolkit import ANSI
from prompt_toolkit.buffer import Buffer
from prompt_toolkit.widgets import Frame
from prompt_toolkit.layout.containers import Window
from prompt_toolkit.layout.controls import BufferControl, FormattedTextControl
from prompt_toolkit.lexers import PygmentsLexer
from pygments.lexers.python import PythonLexer  # type: ignore
from rich.syntax import Syntax
from rich.markdown import Markdown
from rich.console import Console

# TODO: take language into account
lexer: PygmentsLexer = PygmentsLexer(PythonLexer)

EMPTY_PREFIX: Window = Window(width=10)

console = Console()


def get_output_text_and_height(outputs: List[Dict[str, Any]]):
    text_list = []
    height = 0
    for output in outputs:
        if output["output_type"] == "stream":
            text = "".join(output["text"])
            height += text.count("\n") or 1
            if output["name"] == "stderr":
                with console.capture() as capture:
Пример #8
0
    def __init__(self, history):
        search_toolbar = SearchToolbar()

        self.help_buffer_control = BufferControl(
            buffer=history.help_buffer,
            lexer=PygmentsLexer(RstLexer))

        help_window = _create_popup_window(
            title='History Help',
            body=Window(
                content=self.help_buffer_control,
                right_margins=[ScrollbarMargin(display_arrows=True)],
                scroll_offsets=ScrollOffsets(top=2, bottom=2)))

        self.default_buffer_control = BufferControl(
            buffer=history.default_buffer,
            input_processors=[GrayExistingText(history.history_mapping)],
            lexer=PygmentsLexer(PythonLexer))

        self.history_buffer_control = BufferControl(
            buffer=history.history_buffer,
            lexer=PygmentsLexer(PythonLexer),
            search_buffer_control=search_toolbar.control,
            preview_search=True)

        history_window = Window(
            content=self.history_buffer_control,
            wrap_lines=False,
            left_margins=[HistoryMargin(history)],
            scroll_offsets=ScrollOffsets(top=2, bottom=2))

        self.root_container = HSplit([
            #  Top title bar.
            Window(
                content=FormattedTextControl(_get_top_toolbar_fragments),
                align=WindowAlign.CENTER,
                style='class:status-toolbar'),
            FloatContainer(
                content=VSplit([
                    # Left side: history.
                    history_window,
                    # Separator.
                    Window(width=D.exact(1),
                           char=BORDER.LIGHT_VERTICAL,
                           style='class:separator'),
                    # Right side: result.
                    Window(
                        content=self.default_buffer_control,
                        wrap_lines=False,
                        left_margins=[ResultMargin(history)],
                        scroll_offsets=ScrollOffsets(top=2, bottom=2)),
                ]),
                floats=[
                    # Help text as a float.
                    Float(width=60, top=3, bottom=2,
                          content=ConditionalContainer(
                              content=help_window, filter=has_focus(history.help_buffer))),
                ]
            ),
            # Bottom toolbars.
            ArgToolbar(),
            search_toolbar,
            Window(
                content=FormattedTextControl(
                    partial(_get_bottom_toolbar_fragments, history=history)),
                style='class:status-toolbar'),
        ])

        self.layout = Layout(self.root_container, history_window)
Пример #9
0

def get_statusbar_text():
    return " Press Ctrl-C to open menu. "


def get_statusbar_right_text():
    return " {}:{}  ".format(
        text_field.document.cursor_position_row + 1,
        text_field.document.cursor_position_col + 1,
    )


search_toolbar = SearchToolbar()
text_field = TextArea(
    lexer=DynamicLexer(lambda: PygmentsLexer.from_filename(
        ApplicationState.current_path or ".txt", sync_from_start=False)),
    scrollbar=True,
    line_numbers=True,
    search_field=search_toolbar,
)


class TextInputDialog:
    def __init__(self, title="", label_text="", completer=None):
        self.future = Future()

        def accept_text(buf):
            get_app().layout.focus(ok_button)
            buf.complete_state = None
            return True
Пример #10
0
    def singleline(self,
                   auto_suggest=None,
                   enable_history_search=True,
                   multiline=True,
                   **kwargs):
        """Reads a single line of input from the shell. The store_in_history
        kwarg flags whether the input should be stored in PTK's in-memory
        history.
        """
        events.on_pre_prompt_format.fire()
        env = builtins.__xonsh__.env
        mouse_support = env.get("MOUSE_SUPPORT")
        auto_suggest = auto_suggest if env.get("AUTO_SUGGEST") else None
        refresh_interval = env.get("PROMPT_REFRESH_INTERVAL")
        refresh_interval = refresh_interval if refresh_interval > 0 else None
        complete_in_thread = env.get("COMPLETION_IN_THREAD")
        completions_display = env.get("COMPLETIONS_DISPLAY")
        complete_style = self.completion_displays_to_styles[
            completions_display]

        complete_while_typing = env.get("UPDATE_COMPLETIONS_ON_KEYPRESS")
        if complete_while_typing:
            # PTK requires history search to be none when completing while typing
            enable_history_search = False
        if HAS_PYGMENTS:
            self.styler.style_name = env.get("XONSH_COLOR_STYLE")
        completer = None if completions_display == "none" else self.pt_completer

        events.on_timingprobe.fire(name="on_pre_prompt_tokenize")
        get_bottom_toolbar_tokens = self.bottom_toolbar_tokens
        if env.get("UPDATE_PROMPT_ON_KEYPRESS"):
            get_prompt_tokens = self.prompt_tokens
            get_rprompt_tokens = self.rprompt_tokens
        else:
            get_prompt_tokens = self.prompt_tokens()
            get_rprompt_tokens = self.rprompt_tokens()
            if get_bottom_toolbar_tokens:
                get_bottom_toolbar_tokens = get_bottom_toolbar_tokens()
        events.on_timingprobe.fire(name="on_post_prompt_tokenize")

        if env.get("VI_MODE"):
            editing_mode = EditingMode.VI
        else:
            editing_mode = EditingMode.EMACS

        if env.get("XONSH_HISTORY_MATCH_ANYWHERE"):
            self.prompter.default_buffer._history_matches = MethodType(
                _cust_history_matches, self.prompter.default_buffer)
        elif (self.prompter.default_buffer._history_matches
              is not self._history_matches_orig):
            self.prompter.default_buffer._history_matches = self._history_matches_orig

        prompt_args = {
            "mouse_support": mouse_support,
            "auto_suggest": auto_suggest,
            "message": get_prompt_tokens,
            "rprompt": get_rprompt_tokens,
            "bottom_toolbar": get_bottom_toolbar_tokens,
            "completer": completer,
            "multiline": multiline,
            "editing_mode": editing_mode,
            "prompt_continuation": self.continuation_tokens,
            "enable_history_search": enable_history_search,
            "reserve_space_for_menu": 0,
            "key_bindings": self.key_bindings,
            "complete_style": complete_style,
            "complete_while_typing": complete_while_typing,
            "include_default_pygments_style": False,
            "refresh_interval": refresh_interval,
            "complete_in_thread": complete_in_thread,
        }

        if env.get("COLOR_INPUT"):
            events.on_timingprobe.fire(name="on_pre_prompt_style")
            if HAS_PYGMENTS:
                prompt_args["lexer"] = PygmentsLexer(pyghooks.XonshLexer)
                style = style_from_pygments_cls(
                    pyghooks.xonsh_style_proxy(self.styler))
            else:
                style = style_from_pygments_dict(DEFAULT_STYLE_DICT)
            prompt_args["style"] = style
            events.on_timingprobe.fire(name="on_post_prompt_style")

            style_overrides_env = env.get("PTK_STYLE_OVERRIDES")
            if style_overrides_env:
                try:
                    style_overrides = Style.from_dict(style_overrides_env)
                    prompt_args["style"] = merge_styles(
                        [style, style_overrides])
                except (AttributeError, TypeError, ValueError):
                    print_exception()

        if env["ENABLE_ASYNC_PROMPT"]:
            # once the prompt is done, update it in background as each future is completed
            prompt_args["pre_run"] = self.prompt_formatter.start_update

        events.on_pre_prompt.fire()
        line = self.prompter.prompt(**prompt_args)
        events.on_post_prompt.fire()
        return line
Пример #11
0
    def init_prompt_toolkit_cli(self):
        if self.simple_prompt or ('JUPYTER_CONSOLE_TEST' in os.environ):
            # Simple restricted interface for tests so we can find prompts with
            # pexpect. Multi-line input not supported.
            def prompt():
                return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
            self.prompt_for_code = prompt
            self.print_out_prompt = \
                lambda: print('Out[%d]: ' % self.execution_count, end='')
            return

        kb = KeyBindings()
        insert_mode = vi_insert_mode | emacs_insert_mode

        @kb.add("enter", filter=(has_focus(DEFAULT_BUFFER)
                                 & ~has_selection
                                 & insert_mode
                                 ))
        def _(event):
            b = event.current_buffer
            d = b.document
            if not (d.on_last_line or d.cursor_position_row >= d.line_count
                                           - d.empty_line_count_at_the_end()):
                b.newline()
                return

            # Pressing enter flushes any pending display. This also ensures
            # the displayed execution_count is correct.
            self.handle_iopub()

            more, indent = self.check_complete(d.text)

            if (not more) and b.accept_handler:
                b.validate_and_handle()
            else:
                b.insert_text('\n' + indent)

        @kb.add("c-c", filter=has_focus(DEFAULT_BUFFER))
        def _(event):
            event.current_buffer.reset()

        @kb.add("c-\\", filter=has_focus(DEFAULT_BUFFER))
        def _(event):
            raise EOFError

        @kb.add("c-z", filter=Condition(lambda: suspend_to_background_supported()))
        def _(event):
            event.cli.suspend_to_background()

        # Pre-populate history from IPython's history database
        history = InMemoryHistory()
        last_cell = u""
        for _, _, cell in self.history_manager.get_tail(self.history_load_length,
                                                        include_latest=True):
            # Ignore blank lines and consecutive duplicates
            cell = cast_unicode_py2(cell.rstrip())
            if cell and (cell != last_cell):
                history.append_string(cell)

        style_overrides = {
            Token.Prompt: '#009900',
            Token.PromptNum: '#00ff00 bold',
            Token.OutPrompt: '#ff2200',
            Token.OutPromptNum: '#ff0000 bold',
        }
        if self.highlighting_style:
            style_cls = get_style_by_name(self.highlighting_style)
        else:
            style_cls = get_style_by_name('default')
            # The default theme needs to be visible on both a dark background
            # and a light background, because we can't tell what the terminal
            # looks like. These tweaks to the default theme help with that.
            style_overrides.update({
                Token.Number: '#007700',
                Token.Operator: 'noinherit',
                Token.String: '#BB6622',
                Token.Name.Function: '#2080D0',
                Token.Name.Class: 'bold #2080D0',
                Token.Name.Namespace: 'bold #2080D0',
            })
        style_overrides.update(self.highlighting_style_overrides)
        style = merge_styles([
            style_from_pygments_cls(style_cls),
            style_from_pygments_dict(style_overrides),
        ])

        editing_mode = getattr(EditingMode, self.editing_mode.upper())
        langinfo = self.kernel_info.get('language_info', {})
        lexer = langinfo.get('pygments_lexer', langinfo.get('name', 'text'))

        # If enabled in the settings, highlight matching brackets
        # when the DEFAULT_BUFFER has the focus
        input_processors = [ConditionalProcessor(
            processor=HighlightMatchingBracketProcessor(chars='[](){}'),
            filter=has_focus(DEFAULT_BUFFER) & ~is_done &
            Condition(lambda: self.highlight_matching_brackets))
        ]

        self.pt_cli = PromptSession(
            message=(lambda: PygmentsTokens(self.get_prompt_tokens())),
            multiline=True,
            editing_mode=editing_mode,
            lexer=PygmentsLexer(get_pygments_lexer(lexer)),
            prompt_continuation=(
                lambda width, lineno, is_soft_wrap:
                PygmentsTokens(self.get_continuation_tokens(width))
            ),
            key_bindings=kb,
            history=history,
            completer=JupyterPTCompleter(self.Completer),
            enable_history_search=True,
            style=style,
            input_processors=input_processors,
            color_depth=(ColorDepth.TRUE_COLOR if self.true_color else None),

        )
Пример #12
0
def start_repl(p, prompt=' >> '):
    save_last = '_'   # XXX A little hacky

    p.set_output_format('rich')

    display = p._display
    console = display.console
    console.print(f"[purple]Preql {__version__} interactive prompt. Type help() for help[/purple]")

    try:
        session = PromptSession(
            style=style_from_pygments_cls(PreqlStyle),
            lexer=PygmentsLexer(GoLexer),
            completer=Autocompleter(p.interp.state),
            # key_bindings=kb
            validator=MyValidator(),
            history=FileHistory(str(Path.home() / '.preql_history')),
            auto_suggest=AutoSuggestFromHistory(),
            color_depth=ColorDepth.TRUE_COLOR,
        )

        @Condition
        def multiline_filter():
            text = get_app().layout.get_buffer_by_name('DEFAULT_BUFFER').text
            return not _code_is_valid(text)

        while True:
            # Read
            try:
                code = session.prompt(prompt, multiline=multiline_filter)
                if not code.strip():
                    continue


                start_time = time()
                try:
                    if code == '.':
                        with context(state=p.interp.state):
                            console.print(table_more(), overflow='ellipsis')
                        continue

                    # Evaluate (Really just compile)
                    res = p._run_code(code, '<repl>')

                    # Print
                    if res is not None and res is not objects.null:
                        assert isinstance(res, Object), (res, type(res))

                        if save_last:
                            p.interp.set_var(save_last, res)

                        with context(state=p.interp.state):
                            res_repr = res.repr()

                        # repl_log.info(res)
                        if isinstance(res_repr, str) and res.type == T.string:  # Not text
                            if len(res_repr) > 200:
                                res_repr = res_repr[:100] + "..." + res_repr[-100:]    # smarter limit?
                        display.print(res_repr)

                except Signal as s:
                    display.print_exception(s)
                    # repl_log.error(s)
                    # p.interp.set_var('_e', objects.ExceptionInstance(e))
                    continue
                except ExitInterp as e:
                    return e.value
                except Exception as e:
                    repl_log.exception(e)
                    raise
                    # continue

                duration = time() - start_time
                if duration > 1:
                    repl_log.info("(Query took %.2f seconds)" % duration)

            except KeyboardInterrupt:
                repl_log.info("Interrupted (Ctrl+C)")



    except (KeyboardInterrupt, EOFError):
        repl_log.info('Exiting Preql interaction')
Пример #13
0
def text_area(title, text, lexer_name="", height=10, full_screen=False):
    """
    Small implementation of an editor/pager for small pieces of text.

    :param title: Title of the text_area
    :type  title: str
    :param text: Editable text
    :type  text: str
    :param lexer_name: If the editable text should be highlighted with
        some kind of grammar, examples are ``yaml``, ``python`` ...
    :type  lexer_name: str
    :param height: Max height of the text area
    :type  height: int
    :param full_screen: Wether or not the text area should be full screen.
    :type  full_screen: bool
    """
    from prompt_toolkit import Application
    from prompt_toolkit.enums import EditingMode
    from prompt_toolkit.buffer import Buffer
    from prompt_toolkit.layout.containers import HSplit, Window, WindowAlign
    from prompt_toolkit.layout.controls import (BufferControl,
                                                FormattedTextControl)
    from prompt_toolkit.layout.layout import Layout
    from prompt_toolkit.layout import Dimension
    from prompt_toolkit.key_binding import KeyBindings
    from prompt_toolkit.lexers import PygmentsLexer
    from pygments.lexers import find_lexer_class_by_name
    assert (type(title) == str)
    assert (type(text) == str)
    assert (type(lexer_name) == str)
    assert (type(height) == int)
    assert (type(full_screen) == bool)

    kb = KeyBindings()
    buffer1 = Buffer()
    buffer1.text = text

    @kb.add('c-q')
    def exit_(event):
        event.app.exit(0)

    @kb.add('c-s')
    def save_(event):
        event.app.return_text = buffer1.text

    class App(Application):
        return_text = None

    text_height = Dimension(min=0, max=height) if height is not None else None

    pygment_lexer = find_lexer_class_by_name(lexer_name)
    lexer = PygmentsLexer(pygment_lexer)
    text_window = Window(height=text_height,
                         content=BufferControl(buffer=buffer1, lexer=lexer))

    root_container = HSplit([
        Window(char='-',
               align=WindowAlign.CENTER,
               height=1,
               content=FormattedTextControl(text=[('fg:ansiblack bg:ansiwhite',
                                                   title)]),
               always_hide_cursor=True),
        text_window,
        Window(height=1,
               width=None,
               align=WindowAlign.CENTER,
               char='-',
               content=FormattedTextControl(
                   text=[('fg:ansiblack bg:ansiwhite',
                          "Quit [Ctrl-q]  Save [Ctrl-s]")])),
    ])

    layout = Layout(root_container)

    layout.focus(text_window)

    app = App(editing_mode=(EditingMode.EMACS if papis.config.get(
        'editmode', section='tui') == 'emacs' else EditingMode.VI),
              layout=layout,
              key_bindings=kb,
              full_screen=full_screen)
    app.run()
    return app.return_text
Пример #14
0
    def _build_cli(self, history):
        """
            Builds prompt session.
            NOTE: PROMPT-SESSION USES THIS AS DEPENDENCY.
        """
        def get_message():
            prompt = self.get_prompt(self.prompt_format)
            return [(u'class:prompt', prompt)]

        def get_continuation(width, line_number, is_soft_wrap):
            """
                NOTE: updating parameters will cause prompt session to crash.
            """
            # pylint: disable=unused-argument
            continuation = self.multiline_continuation_char * (width - 1) + ' '
            return [(u'class:continuation', continuation)]

        get_toolbar_tokens = create_toolbar_tokens_func(self)

        if self.wider_completion_menu:
            complete_style = CompleteStyle.MULTI_COLUMN
        else:
            complete_style = CompleteStyle.COLUMN

        with self._completer_lock:
            self.prompt_session = PromptSession(
                message=get_message,
                style=style_factory(self.syntax_style, self.cli_style),

                # Layout options.
                lexer=PygmentsLexer(PostgresLexer),
                prompt_continuation=get_continuation,
                bottom_toolbar=get_toolbar_tokens,
                complete_style=complete_style,
                input_processors=[
                    ConditionalProcessor(
                        processor=HighlightMatchingBracketProcessor(
                            chars='[](){}'),
                        #pylint: disable=invalid-unary-operand-type
                        filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()),
                    # Render \t as 4 spaces instead of "^I"
                    TabsProcessor(char1=u' ', char2=u' ')
                ],
                reserve_space_for_menu=self.min_num_menu_lines,

                # Buffer options.
                multiline=mssql_is_multiline(self),
                completer=ThreadedCompleter(
                    DynamicCompleter(lambda: self.completer)),
                history=history,
                auto_suggest=AutoSuggestFromHistory(),
                complete_while_typing=True,

                # Key bindings.
                enable_system_prompt=True,
                enable_open_in_editor=True,

                # Other options.
                key_bindings=mssqlcli_bindings(self),
                editing_mode=EditingMode.VI
                if self.vi_mode else EditingMode.EMACS,
                search_ignore_case=True)

            return self.prompt_session
Пример #15
0
    def singleline(
        self, auto_suggest=None, enable_history_search=True, multiline=True, **kwargs
    ):
        """Reads a single line of input from the shell. The store_in_history
        kwarg flags whether the input should be stored in PTK's in-memory
        history.
        """
        events.on_pre_prompt.fire()
        env = builtins.__xonsh__.env
        mouse_support = env.get("MOUSE_SUPPORT")
        auto_suggest = auto_suggest if env.get("AUTO_SUGGEST") else None
        completions_display = env.get("COMPLETIONS_DISPLAY")
        complete_style = self.completion_displays_to_styles[completions_display]

        complete_while_typing = env.get("UPDATE_COMPLETIONS_ON_KEYPRESS")
        if complete_while_typing:
            # PTK requires history search to be none when completing while typing
            enable_history_search = False
        if HAS_PYGMENTS:
            self.styler.style_name = env.get("XONSH_COLOR_STYLE")
        completer = None if completions_display == "none" else self.pt_completer

        if env.get("UPDATE_PROMPT_ON_KEYPRESS"):
            get_prompt_tokens = self.prompt_tokens
            get_rprompt_tokens = self.rprompt_tokens
            get_bottom_toolbar_tokens = self.bottom_toolbar_tokens
        else:
            get_prompt_tokens = self.prompt_tokens()
            get_rprompt_tokens = self.rprompt_tokens()
            get_bottom_toolbar_tokens = self.bottom_toolbar_tokens()

        if env.get("VI_MODE"):
            editing_mode = EditingMode.VI
        else:
            editing_mode = EditingMode.EMACS

        if env.get("XONSH_HISTORY_MATCH_ANYWHERE"):
            self.prompter.default_buffer._history_matches = MethodType(
                _cust_history_matches, self.prompter.default_buffer
            )
        elif (
            self.prompter.default_buffer._history_matches
            is not self._history_matches_orig
        ):
            self.prompter.default_buffer._history_matches = self._history_matches_orig

        prompt_args = {
            "mouse_support": mouse_support,
            "auto_suggest": auto_suggest,
            "message": get_prompt_tokens,
            "rprompt": get_rprompt_tokens,
            "bottom_toolbar": get_bottom_toolbar_tokens,
            "completer": completer,
            "multiline": multiline,
            "editing_mode": editing_mode,
            "prompt_continuation": self.continuation_tokens,
            "enable_history_search": enable_history_search,
            "reserve_space_for_menu": 0,
            "key_bindings": self.key_bindings,
            "complete_style": complete_style,
            "complete_while_typing": complete_while_typing,
            "include_default_pygments_style": False,
        }
        if builtins.__xonsh__.env.get("COLOR_INPUT"):
            if HAS_PYGMENTS:
                prompt_args["lexer"] = PygmentsLexer(pyghooks.XonshLexer)
                style = style_from_pygments_cls(pyghooks.xonsh_style_proxy(self.styler))
            else:
                style = style_from_pygments_dict(DEFAULT_STYLE_DICT)

            prompt_args["style"] = style

        line = self.prompter.prompt(**prompt_args)
        events.on_post_prompt.fire()
        return line
Пример #16
0
    def __init__(self, debugger):
        self._filename = None
        self.sources = {}
        self.debugger = debugger
        self.debugger.events.on_stop += self.on_stop
        self.current_address_margin = CurrentAddressMargin()
        kb = KeyBindings()
        self.locals_processor = DisplayVariablesProcessor()

        self.source_buffer = Buffer(multiline=True)
        self.bar_buffer = Buffer(multiline=True)
        self.register_buffer = Buffer(multiline=True)
        self.logs_buffer = Buffer(multiline=True)

        @kb.add(Keys.F10, eager=True)
        def quit_(event):
            event.app.exit()

        @kb.add(Keys.F8)
        def clear_breakpoint_(event):
            if self.has_source():
                filename, row = self.get_current_location()
                self.debugger.clear_breakpoint(filename, row)

        @kb.add(Keys.F7)
        def set_breakpoint_(event):
            if self.has_source():
                filename, row = self.get_current_location()
                self.debugger.set_breakpoint(filename, row)

        @kb.add(Keys.F6)
        def step_(event):
            self.debugger.step()

        @kb.add(Keys.F5)
        def run_(event):
            self.debugger.run()

        @kb.add(Keys.F4)
        def stop_(event):
            self.debugger.stop()

        @kb.add(Keys.PageUp)
        def scroll_up_(event):
            self.source_buffer.cursor_up(count=15)

        @kb.add(Keys.PageDown)
        def scroll_down_(event):
            self.source_buffer.cursor_down(count=15)

        src_lexer = PygmentsLexer(CLexer)

        source_code_window = Window(
            content=BufferControl(
                buffer=self.source_buffer,
                lexer=src_lexer,
                input_processors=[self.locals_processor],
            ),
            left_margins=[self.current_address_margin,
                          NumberedMargin()],
            right_margins=[ScrollbarMargin(display_arrows=True)],
            cursorline=True,
        )

        register_window = Window(
            content=BufferControl(buffer=self.register_buffer), width=20)

        title_text = "Welcome to the ppci debugger version {} running in prompt_toolkit {}".format(
            ppci_version, ptk_version)

        help_text = ("F4=stop F5=run F6=step F7=set breakpoint" +
                     " F8=clear breakpoint F10=exit")

        # Application layout:
        body = HSplit([
            Window(content=FormattedTextControl(text=title_text), height=1),
            VSplit([
                HSplit([
                    Frame(
                        body=source_code_window,
                        title="source-code",
                    ),
                    Window(
                        content=BufferControl(buffer=self.logs_buffer),
                        height=2,
                    ),
                ]),
                Frame(body=register_window, title="registers"),
            ]),
            Window(
                content=FormattedTextControl(self.get_status_tokens),
                height=1,
            ),
            Window(content=FormattedTextControl(help_text), height=1),
        ])
        layout = Layout(body)

        style = style_from_pygments_cls(get_style_by_name("vim"))

        log_handler = MyHandler(self.logs_buffer)
        fmt = logging.Formatter(fmt=logformat)
        log_handler.setFormatter(fmt)
        log_handler.setLevel(logging.DEBUG)
        logging.getLogger().setLevel(logging.DEBUG)
        logging.getLogger().addHandler(log_handler)

        self._event_loop = get_event_loop()

        self.application = Application(layout=layout,
                                       style=style,
                                       key_bindings=kb,
                                       full_screen=True)
Пример #17
0
    def __init__(self, project=None, extra_locals=None):
        """
        Launch the Brownie console.

        Arguments
        ---------
        project : `Project`, optional
            Active Brownie project to include in the console's local namespace.
        extra_locals: dict, optional
            Additional variables to add to the console namespace.
        """
        console_settings = CONFIG.settings["console"]

        locals_dict = dict((i, getattr(brownie, i)) for i in brownie.__all__)
        locals_dict.update(_dir=dir,
                           dir=self._dir,
                           exit=_Quitter("exit"),
                           quit=_Quitter("quit"))

        if project:
            project._update_and_register(locals_dict)

        # only make GUI available if Tkinter is installed
        try:
            Gui = importlib.import_module("brownie._gui").Gui
            locals_dict["Gui"] = Gui
        except ModuleNotFoundError:
            pass

        if extra_locals:
            locals_dict.update(extra_locals)

        # prepare lexer and formatter
        self.lexer = PythonLexer()
        fmt_name = "terminal"
        try:
            import curses

            curses.setupterm()
            if curses.tigetnum("colors") == 256:
                fmt_name = "terminal256"
        except Exception:
            # if curses won't import we are probably using Windows
            pass
        self.formatter = get_formatter_by_name(
            fmt_name, style=console_settings["color_style"])

        # create prompt session object
        history_file = str(_get_data_folder().joinpath(".history").absolute())
        kwargs = {}
        if console_settings["show_colors"]:
            kwargs.update(
                lexer=PygmentsLexer(PythonLexer),
                style=style_from_pygments_cls(
                    get_style_by_name(console_settings["color_style"])),
                include_default_pygments_style=False,
            )
        if console_settings["auto_suggest"]:
            kwargs["auto_suggest"] = TestAutoSuggest(locals_dict)
        if console_settings["completions"]:
            kwargs["completer"] = ConsoleCompleter(locals_dict)
        self.prompt_session = PromptSession(
            history=SanitizedFileHistory(history_file, locals_dict),
            input=self.prompt_input,
            **kwargs,
        )

        if console_settings["auto_suggest"]:
            # remove the builting binding for auto-suggest acceptance
            key_bindings = self.prompt_session.app.key_bindings
            accept_binding = key_bindings.get_bindings_for_keys(("right", ))[0]
            key_bindings._bindings2.remove(accept_binding.handler)

        super().__init__(locals_dict)
Пример #18
0
client.start()

data = client.send('listCommands', {}, True)
data = list(map(lambda c: c['name'], data))

sql_completer = WordCompleter(data, ignore_case=True)

style = Style.from_dict({
    'completion-menu.completion': 'bg:#008888 #ffffff',
    'completion-menu.completion.current': 'bg:#00aaaa #000000',
    'scrollbar.background': 'bg:#88aaaa',
    'scrollbar.button': 'bg:#222222',
})

session = PromptSession(history=FileHistory('./.main-prompt-history'),
                        lexer=PygmentsLexer(InputLexer),
                        completer=sql_completer,
                        style=style_from_pygments_cls(
                            get_style_by_name(u'monokai')),
                        reserve_space_for_menu=2)

while True:
    try:
        text = session.prompt('>>> ', auto_suggest=AutoSuggestFromHistory())
    except KeyboardInterrupt:
        continue
    except EOFError:
        break
    else:
        #print('You entered:', text)
        res = client.send('execCommand', {'payload': text}, True)
Пример #19
0
def cmd_loop(
    context: Context = None,
    client: dask.distributed.Client = None,
    startup=False,
    log_level=None,
):  # pragma: no cover
    """
    Run a REPL for answering SQL queries using ``dask-sql``.
    Every SQL expression that ``dask-sql`` understands can be used here.

    Args:
        context (:obj:`dask_sql.Context`): If set, use this context instead of an empty one.
        client (:obj:`dask.distributed.Client`): If set, use this dask client instead of a new one.
        startup (:obj:`bool`): Whether to wait until Apache Calcite was loaded
        log_level: (:obj:`str`): The log level of the server and dask-sql

    Example:
        It is possible to run a REPL by using the CLI script in ``dask-sql``
        or by calling this function directly in your user code:

        .. code-block:: python

            from dask_sql import cmd_loop

            # Create your pre-filled context
            c = Context()
            ...

            cmd_loop(context=c)

        Of course, it is also possible to call the usual ``CREATE TABLE``
        commands.
    """
    pd.set_option("display.max_rows", None)
    pd.set_option("display.max_columns", None)
    pd.set_option("display.width", None)
    pd.set_option("display.max_colwidth", None)

    logging.basicConfig(level=log_level)

    client = client or dask.distributed.Client()
    context = context or Context()

    if startup:
        context.sql("SELECT 1 + 1").compute()

    session = PromptSession(lexer=PygmentsLexer(SqlLexer))

    while True:
        try:
            text = session.prompt("(dask-sql) > ")
        except KeyboardInterrupt:
            continue
        except EOFError:
            break

        text = text.rstrip(";").strip()

        if not text:
            continue

        try:
            df = context.sql(text, return_futures=False)
            print(df)
        except Exception as e:
            print(e)
Пример #20
0
def cmd_loop(
    context: Context = None,
    client: Client = None,
    startup=False,
    log_level=None,
):  # pragma: no cover
    """
    Run a REPL for answering SQL queries using ``dask-sql``.
    Every SQL expression that ``dask-sql`` understands can be used here.

    Args:
        context (:obj:`dask_sql.Context`): If set, use this context instead of an empty one.
        client (:obj:`dask.distributed.Client`): If set, use this dask client instead of a new one.
        startup (:obj:`bool`): Whether to wait until Apache Calcite was loaded
        log_level: (:obj:`str`): The log level of the server and dask-sql

    Example:
        It is possible to run a REPL by using the CLI script in ``dask-sql``
        or by calling this function directly in your user code:

        .. code-block:: python

            from dask_sql import cmd_loop

            # Create your pre-filled context
            c = Context()
            ...

            cmd_loop(context=c)

        Of course, it is also possible to call the usual ``CREATE TABLE``
        commands.
    """
    pd.set_option("display.max_rows", None)
    pd.set_option("display.max_columns", None)
    pd.set_option("display.width", None)
    pd.set_option("display.max_colwidth", None)

    logging.basicConfig(level=log_level)

    client = client or Client()
    context = context or Context()

    if startup:
        context.sql("SELECT 1 + 1").compute()

    session = CompatiblePromptSession(lexer=PygmentsLexer(SqlLexer))

    while True:
        try:
            text = session.prompt("(dask-sql) > ")
        except KeyboardInterrupt:
            continue
        except EOFError:
            break

        text = text.rstrip(";").strip()

        if not text:
            continue

        meta_command_detected = _meta_commands(text, context=context, client=client)
        if isinstance(meta_command_detected, Client):
            client = meta_command_detected

        if not meta_command_detected:
            try:
                df = context.sql(text, return_futures=True)
                if df is not None:  # some sql commands returns None
                    df = df.persist()
                    # Now turn it into a list of futures
                    futures = client.futures_of(df)
                    with ProgressBar() as pb:
                        for _ in pb(
                            as_completed(futures), total=len(futures), label="Executing"
                        ):
                            continue
                        df = df.compute()
                        print(df.to_markdown(tablefmt="fancy_grid"))

            except Exception:
                traceback.print_exc()
Пример #21
0
def create_radian_prompt_session(options, settings):

    local_history_file = settings.local_history_file
    global_history_file = settings.global_history_file
    if options.no_history:
        history = ModalInMemoryHistory()
    elif not options.global_history and os.path.exists(local_history_file):
        history = ModalFileHistory(os.path.abspath(local_history_file))
    else:
        history_file = os.path.join(os.path.expanduser(global_history_file))
        history_file = os.path.expandvars(history_file)
        history_file_dir = os.path.dirname(history_file)
        if not os.path.exists(history_file_dir):
            os.makedirs(history_file_dir, 0o700)
        history = ModalFileHistory(history_file)

    if is_windows():
        output = None
    else:
        output = CustomOutput.from_pty(sys.stdout,
                                       term=get_term_environment_variable())

    def get_inputhook():
        # make testing more robust
        if "RADIAN_NO_INPUTHOOK" in os.environ:
            return None

        terminal_width = [None]

        def _(context):
            output_width = session.app.output.get_size().columns
            if output_width and terminal_width[0] != output_width:
                terminal_width[0] = output_width
                setoption("width", max(terminal_width[0], 20))

            while True:
                if context.input_is_ready():
                    break
                try:
                    if peek_event():
                        with session.app.input.detach():
                            with session.app.input.rare_mode():
                                process_events()
                    else:
                        polled_events()

                except Exception:
                    pass
                time.sleep(1.0 / 30)

        return _

    def vi_mode_prompt():
        if session.editing_mode.lower(
        ) == "vi" and settings.show_vi_mode_prompt:
            im = session.app.vi_state.input_mode
            vi_mode_prompt = settings.vi_mode_prompt
            if isinstance(vi_mode_prompt, string_types):
                return vi_mode_prompt.format(str(im)[3:6])
            else:
                return vi_mode_prompt[str(im)[3:6]]
        return ""

    def message():
        if hasattr(session.current_mode, "get_message"):
            return ANSI(vi_mode_prompt() + session.current_mode.get_message())
        elif hasattr(session.current_mode, "message"):
            message = session.current_mode.message
            if callable(message):
                return ANSI(vi_mode_prompt() + message())
            else:
                return ANSI(vi_mode_prompt() + message)
        else:
            return ""

    session = ModalPromptSession(
        message=message,
        color_depth=ColorDepth.default(term=os.environ.get("TERM")),
        style=style_from_pygments_cls(get_style_by_name(
            settings.color_scheme)),
        editing_mode="VI"
        if settings.editing_mode in ["vim", "vi"] else "EMACS",
        history=history,
        enable_history_search=True,
        history_search_no_duplicates=settings.history_search_no_duplicates,
        search_ignore_case=settings.history_search_ignore_case,
        enable_suspend=True,
        tempfile_suffix=".R",
        input=CustomInput(sys.stdin),
        output=output,
        inputhook=get_inputhook(),
        mode_class=RadianMode,
        auto_suggest=AutoSuggestFromHistory()
        if settings.auto_suggest else None)

    apply_settings(session, settings)

    def browse_activator(session):
        message = session.prompt_text
        if BROWSE_PATTERN.match(message):
            session.browse_level = BROWSE_PATTERN.match(message).group(1)
            return True
        else:
            return False

    def browse_on_pre_accept(session):
        if session.default_buffer.text.strip() in [
                "n", "s", "f", "c", "cont", "Q", "where", "help"
        ]:
            session.add_history = False

    def shell_process_text(session):
        text = session.default_buffer.text
        shell.run_command(text)

    input_processors = []
    if settings.highlight_matching_bracket:
        input_processors.append(HighlightMatchingBracketProcessor())

    session.register_mode(
        "r",
        activator=lambda session: session.prompt_text == settings.prompt,
        insert_new_line=True,
        history_share_with="browse",
        get_message=lambda: settings.prompt,
        multiline=settings.indent_lines,
        complete_while_typing=settings.complete_while_typing,
        lexer=PygmentsLexer(SLexer),
        completer=RCompleter(timeout=settings.completion_timeout),
        key_bindings=create_key_bindings(),
        input_processors=input_processors,
        prompt_key_bindings=create_r_key_bindings(prase_text_complete))
    session.register_mode("shell",
                          on_post_accept=shell_process_text,
                          insert_new_line=True,
                          get_message=lambda: settings.shell_prompt,
                          multiline=settings.indent_lines,
                          complete_while_typing=settings.complete_while_typing,
                          lexer=None,
                          completer=SmartPathCompleter(),
                          prompt_key_bindings=create_shell_key_bindings())
    session.register_mode(
        "browse",
        activator=browse_activator,
        # on_pre_accept=browse_on_pre_accept,  # disable
        insert_new_line=True,
        history_share_with="r",
        get_message=lambda: settings.browse_prompt.format(session.browse_level
                                                          ),
        multiline=settings.indent_lines,
        complete_while_typing=True,
        lexer=PygmentsLexer(SLexer),
        completer=RCompleter(timeout=settings.completion_timeout),
        input_processors=input_processors,
        prompt_key_bindings=create_r_key_bindings(prase_text_complete),
        switchable_from=False,
        switchable_to=False)
    session.register_mode("unknown",
                          insert_new_line=False,
                          get_message=lambda: session.prompt_text,
                          complete_while_typing=False,
                          lexer=None,
                          completer=None,
                          prompt_key_bindings=None,
                          switchable_from=False,
                          switchable_to=False,
                          input_processors=[])

    return session
Пример #22
0
    def run(self, query, data):
        self.load_config()

        if data or query is not None:
            self.format = self.format_stdin
            self.echo.verbose = False

        if self.echo.verbose:
            show_version()

        if not self.connect():
            return

        if self.client:
            self.client.settings = self.settings
            self.client.cli_settings = {
                'multiline': self.multiline,
                'vi_mode': self.vi_mode,
                'format': self.format,
                'format_stdin': self.format_stdin,
                'show_formatted_query': self.show_formatted_query,
                'highlight': self.highlight,
                'highlight_output': self.highlight_output,
                'refresh_metadata_on_start': self.refresh_metadata_on_start,
                'refresh_metadata_on_query': self.refresh_metadata_on_query,
            }

        if data and query is None:
            # cat stuff.sql | clickhouse-cli
            # clickhouse-cli stuff.sql
            for subdata in data:
                self.handle_input(subdata.read(),
                                  verbose=False,
                                  refresh_metadata=False)

            return

        if not data and query is not None:
            # clickhouse-cli -q 'SELECT 1'
            return self.handle_query(query, stream=False)

        if data and query is not None:
            # cat stuff.csv | clickhouse-cli -q 'INSERT INTO stuff'
            # clickhouse-cli -q 'INSERT INTO stuff' stuff.csv
            for subdata in data:
                compress = 'gzip' if os.path.splitext(
                    subdata.name)[1] == '.gz' else False

                self.handle_query(query,
                                  data=subdata,
                                  stream=True,
                                  compress=compress)

            return

        buffer = CLIBuffer(
            client=self.client,
            multiline=self.multiline,
            metadata=self.metadata,
        )

        root_container = Window(content=BufferControl(buffer=buffer))

        layout = Layout(root_container)
        # layout.focus(root_container)

        # layout = prompt(
        #     lexer=PygmentsLexer(CHLexer) if self.highlight else None,
        #     # get_prompt_tokens=get_prompt_tokens,
        #     # get_continuation_tokens=get_continuation_tokens,
        #     multiline=self.multiline,
        # )

        hist = FileHistory(
            filename=os.path.expanduser('~/.clickhouse-cli_history'))
        self.completer = CHCompleter(self.client, self.metadata)

        self.session = PromptSession(
            style=CHStyle if self.highlight else None,
            lexer=PygmentsLexer(CHLexer) if self.highlight else None,
            message=get_prompt_tokens()[0][1],
            prompt_continuation=get_continuation_tokens()[0][1],
            multiline=is_multiline(self.multiline),
            vi_mode=self.vi_mode,
            history=hist,
            key_bindings=kb,
            complete_while_typing=self.complete_while_typing,
            completer=ThreadedCompleter(
                DynamicCompleter(lambda: self.completer)),
        )

        self.app = Application(layout=layout,
                               # buffer=buffer,
                               )

        #self.cli = CommandLineInterface(application=application, eventloop=eventloop)
        if self.refresh_metadata_on_start:
            self.app.current_buffer.completer.refresh_metadata()

        try:
            while True:
                try:
                    cli_input = self.session.prompt()
                    self.handle_input(cli_input)
                except KeyboardInterrupt:
                    # Attempt to terminate queries
                    for query_id in self.query_ids:
                        self.client.kill_query(query_id)

                    self.echo.error("\nQuery was terminated.")
                finally:
                    self.query_ids = []
        except EOFError:
            self.echo.success("Bye.")
Пример #23
0
        return ''
    else:  # 无输入
        width = os.get_terminal_size().columns
        result = json.loads(base64.b85decode(pyperclip.paste().strip()))
        return f'''
{" STDOUT ":=^{width}}
{result["o"]}

{" STDERR ":=^{width}}
{result["e"]}
        '''


if __name__ == '__main__':
    session = PromptSession(
        lexer=PygmentsLexer(BashLexer),
        completer=WordCompleter({}, ignore_case=False),
        complete_while_typing=False,
        key_bindings=_bind(),
        multiline=True,
        prompt_continuation=_prompt_continuation,
    )
    count = 0
    while True:
        try:
            text = session.prompt(
                HTML('<green>{}</green>').format(f'In [{count}]: ')).strip()
        except KeyboardInterrupt:
            continue
        except EOFError:
            break
Пример #24
0
def main():
    init_logger()
    logger = get_logger()

    for action in [
            config,
            list_device,
            playlist_create,
            playlist_delete,
            playlist_list,
            playlist_refresh,
            playlist_update,
            playlist_view,
            playlist_rename,
    ]:
        NO_SERVER_ACTION.append(action)

    parser = argparse.ArgumentParser()
    wrap_parser_exit(parser)

    create_args(parser)

    args = parser.parse_args()
    logger.info(args)

    if not hasattr(args, 'func'):
        from prompt_toolkit_ext import PromptArgumentParser, run_prompt, LimitSizeFileHistory
        from prompt_toolkit_ext.completer import ArgParserCompleter
        from prompt_toolkit_ext.lexer import ArgParseLexer
        prompt_argparser = PromptArgumentParser()
        subparsers = create_args(prompt_argparser)
        create_quit_parser(subparsers)
        history = LimitSizeFileHistory(get_history_file_path(), 100)
        from prompt_toolkit.lexers import PygmentsLexer
        try:
            print('=' * 80)
            print('pysimpledlna v0.5.4', '投屏工具')
            print('用户数据目录:', get_user_data_dir())
            print('日志文件:', get_log_file_path())
            print('=' * 80)
            run_prompt(prompt_parser=prompt_argparser,
                       prompt_history=history,
                       prompt_completer=ArgParserCompleter(prompt_argparser),
                       prompt_lexer=PygmentsLexer(ArgParseLexer))
        except KeyboardInterrupt:
            quit_prog()
        except Exception as e:
            logger.info(traceback.format_exc())
            print(e)
        return

    need_server_started = args.func not in NO_SERVER_ACTION
    try:
        if need_server_started:
            default_port = settings.get_default_port()
            try_cnt = 0
            while is_tcp_port_occupied(_DLNA_SERVER.server_ip, default_port):
                default_port += 1
                if default_port > 18020:
                    default_port = default_port % 20 + 18000
                try_cnt += 1
                if try_cnt >= 20:
                    print('没有可用的端口:', default_port)
                    sys.exit()
            settings.set_default_port(default_port)
            settings.write()
            _DLNA_SERVER.server_port = default_port
            _DLNA_SERVER.start_server()
        args.func(args)
    finally:
        if need_server_started:
            _DLNA_SERVER.stop_server()
Пример #25
0
        def _process_input(self, reactor):
            if not self._quiet:
                self._print_startup_message()

            while self._ready.wait(0.5) != True:
                if not reactor.is_running():
                    return

            while True:
                expression = ""
                line = ""
                while len(expression) == 0 or line.endswith("\\"):
                    if not reactor.is_running():
                        return

                    prompt = "[%s]" % self._prompt_string + "-> " if len(
                        expression) == 0 else "... "

                    pending_eval = self._pending_eval
                    if pending_eval is not None:
                        if len(pending_eval) > 0:
                            expression = pending_eval.pop(0)
                            if not self._quiet:
                                self._print(prompt + expression)
                        else:
                            self._pending_eval = None
                    else:
                        if self._quiet:
                            self._exit_status = 0 if self._errors == 0 else 1
                            return

                        try:
                            if self._have_terminal:
                                self._cli = PromptSession(
                                    lexer=PygmentsLexer(JavascriptLexer),
                                    history=self._history,
                                    completer=self._completer)

                                line = self._cli.prompt(prompt)
                            else:
                                line = self._dumb_stdin_reader.read_line(
                                    prompt)
                                self._print(line)
                        except EOFError:
                            if not self._have_terminal:
                                while not self._stopping.wait(1):
                                    pass
                            return
                        except KeyboardInterrupt:
                            line = ""
                            if not self._have_terminal:
                                sys.stdout.write("\n" + prompt)
                            continue
                        if len(line.strip()) > 0:
                            if len(expression) > 0:
                                expression += "\n"
                            expression += line.rstrip("\\")

                if expression.endswith("?"):
                    try:
                        self._print_help(expression)
                    except JavaScriptError as e:
                        error = e.error
                        self._print(Fore.RED + Style.BRIGHT + error['name'] +
                                    Style.RESET_ALL + ": " + error['message'])
                    except frida.InvalidOperationError:
                        return
                elif expression.startswith("%"):
                    self._do_magic(expression[1:].rstrip())
                elif expression in ("exit", "quit", "q"):
                    return
                elif expression == "help":
                    self._print("Help: #TODO :)")
                else:
                    if not self._eval_and_print(expression):
                        self._errors += 1
Пример #26
0
def cli(client):
    kb = KeyBindings()

    @kb.add('c-space')
    def _(event):
        """
        Initialize autocompletion, or select the next completion.
        """
        buff = event.app.current_buffer
        if buff.complete_state:
            buff.complete_next()
        else:
            buff.start_completion(select_first=False)

    @kb.add('enter', filter=has_selected_completion)
    def _(event):
        """
        Makes the enter key work as the tab key only when showing the menu.
        """

        event.current_buffer.complete_state = None
        b = event.cli.current_buffer
        b.complete_state = None

    def _process_args(args, string=True):
        kwargs = {}
        execute = True
        skip_index = None
        for i, arg in enumerate(args):
            if i == skip_index:
                continue
            arg = arg.strip()
            if "=" in arg:
                a, val = arg.split("=")
                if not string:
                    if "," in val:
                        val = val.split(",")
                        val = [int(v) for v in val]
                    else:
                        val = int(val)
                kwargs[a] = val
            else:
                a, val = arg, args[i + 1]
                try:
                    if not string:
                        if "," in val:
                            val = val.split(",")
                            val = [int(v) for v in val]
                        else:
                            val = int(val)
                    kwargs[a] = val
                    skip_index = i + 1
                except TypeError:
                    click.secho("Error parsing arguments!", fg='yellow')
                    execute = False
                    break
                except ValueError:
                    click.secho("Error parsing argument", fg='yellow')
                    execute = False
                    break
        return kwargs, execute

    session = PromptSession(lexer=PygmentsLexer(PythonLexer),
                            completer=CmdCompleter(client),
                            style=style,
                            complete_while_typing=True,
                            bottom_toolbar=bottom_toolbar,
                            key_bindings=kb,
                            history=FileHistory('../.pymodhis'),
                            auto_suggest=AutoSuggestFromHistory())
    click.secho("{}".format(TITLE), fg='green')
    result = None
    while True:
        try:

            text = session.prompt('> ', complete_while_typing=True)
            if text.strip().lower() == 'help':
                print_formatted_text(HTML("<u>Available commands:</u>"))
                for cmd, obj in sorted(session.completer.commands.items()):
                    if cmd != 'help':
                        print_formatted_text(
                            HTML("<skyblue>{:45s}</skyblue>"
                                 "<seagreen>{:100s}"
                                 "</seagreen>".format(cmd, obj.help_text)))

                continue
            elif text.strip().lower() == 'exit':
                raise EOFError()
            elif text.strip().lower().startswith("client."):
                try:
                    text = text.strip().split()
                    cmd = text[0].split(".")[1]
                    args = text[1:]
                    kwargs, execute = _process_args(args, string=False)
                    if execute:
                        if text[0] in CLIENT_ATTRIBUTES:
                            result = Result(getattr(client, cmd))
                        else:
                            result = Result(getattr(client, cmd)(**kwargs))
                        result.print_result()
                except Exception as e:
                    click.secho(repr(e), fg='red')
            elif text.strip().lower().startswith("result."):
                if result:
                    words = text.lower().split()
                    if words[0] == 'result.raw':
                        result.raw()
                    if words[0] == 'result.decode':
                        args = words[1:]
                        kwargs, execute = _process_args(args)
                        if execute:
                            result.decode(**kwargs)
        except KeyboardInterrupt:
            continue  # Control-C pressed. Try again.
        except EOFError:
            break  # Control-D pressed.
        except Exception as e:  # Handle all other exceptions
            click.secho(str(e), fg='red')

    click.secho('GoodBye!', fg='blue')
Пример #27
0
    def handle(self) -> None:
        self.console.print(
            f"[bold]Jira-select[/bold] Shell v{__version__}",
            style="dodger_blue1 blink",
        )
        vi_mode = not self.config.shell.emacs_mode
        if self.options.editor_mode:
            vi_mode = self.options.editor_mode
        if vi_mode:
            self.console.print(
                " | [bold]Run:[/bold]\t\tESC->ENTER",
                style="deep_sky_blue4",
            )
            self.console.print(
                " | [bold]Clear:[/bold]\tCTRL+C",
                style="deep_sky_blue4",
            )
            self.console.print(
                " | [bold]Exit:[/bold]\tCTRL+D",
                style="deep_sky_blue4",
            )

        completions = self.build_completions()
        session: PromptSession = PromptSession(
            lexer=PygmentsLexer(YamlLexer),
            multiline=True,
            completer=completions,
            complete_while_typing=False,
            history=FileHistory(os.path.join(get_config_dir(),
                                             "shell_history")),
            auto_suggest=AutoSuggestFromHistory(),
            vi_mode=vi_mode,
            mouse_support=True,
        )
        formatter_cls = get_installed_formatters()[self.options.format]

        output = self.options.output
        if not output:
            output = tempfile.NamedTemporaryFile(
                "wb+",
                suffix=f".{formatter_cls.get_file_extension()}",
            )

        while True:
            try:
                self._prompt_loop(session, formatter_cls, output)
            except JIRAError as e:
                self.console.print(
                    f"[red][bold]Jira Error:[/bold] {e.text}[/red]")
            except QueryError as e:
                self.console.print(f"[red][bold]Query Error:[/bold] {e}[/red]")
            except QueryParseError as e:
                self.console.print(
                    f"[red][bold]Parse Error:[/bold] Your query could not be parsed: {e}[/red]"
                )
            except KeyboardInterrupt:
                continue
            except EOFError:
                break
            except Exception:
                self.console.print_exception()

        output.close()
Пример #28
0
from pygments.lexers.html import HtmlLexer
from prompt_toolkit.shortcuts import prompt
from prompt_toolkit.lexers import PygmentsLexer

text = prompt('Enter HTML: ', lexer=PygmentsLexer(HtmlLexer))
print('You said: %s' % text)


Пример #29
0
def accept_yes():
    get_app().exit(result=True)


def accept_no():
    get_app().exit(result=False)


def do_exit():
    get_app().exit(result=False)


yes_button = Button(text='Yes', handler=accept_yes)
no_button = Button(text='No', handler=accept_no)
textfield  = TextArea(lexer=PygmentsLexer(HtmlLexer))
checkbox1 = Checkbox(text='Checkbox')
checkbox2 = Checkbox(text='Checkbox')

radios = RadioList(values=[
    ('Red', 'red'),
    ('Green', 'green'),
    ('Blue', 'blue'),
    ('Orange', 'orange'),
    ('Yellow', 'yellow'),
    ('Purple', 'Purple'),
    ('Brown', 'Brown'),
])

animal_completer = WordCompleter([
    'alligator', 'ant', 'ape', 'bat', 'bear', 'beaver', 'bee', 'bison',
Пример #30
0
    def run_cli(self):
        print('Version: {0}'.format(__version__))
        print_formatted_text(FormattedText([('ansibrightred', 'W'),
                                            ('orange', 'e'),
                                            ('ansibrightyellow', 'l'),
                                            ('ansibrightgreen', 'c'),
                                            ('blue', 'o'), ('indigo', 'm'),
                                            ('purple', 'e'), ('', '! ')]),
                             end='')
        print_formatted_text(
            FormattedText([
                ('', 'Open an issue here: '),
                ('ansibrightgreen',
                 'https://github.com/RPing/influx-prompt/issues'),
            ]))
        if self.args['database'] is None:
            print_formatted_text(FormattedText([
                ('ansibrightyellow', '[Warning] '),
            ]),
                                 end='')
            print('You haven\'t set database. '
                  'use "use <database>" to specify database.')

        session = PromptSession(lexer=PygmentsLexer(SqlLexer),
                                search_ignore_case=True,
                                history=self.history)

        prompt_text = '{0}> '.format(self.args['username'])
        while True:
            try:
                query = session.prompt(prompt_text,
                                       completer=self.completer,
                                       complete_while_typing=True)
            except KeyboardInterrupt:
                continue
            except EOFError:
                print('Goodbye!')
                return

            query = query.strip()
            if query == '':
                continue

            msg = process_extra_command(self.args, query)
            if msg:
                print(msg)
                continue

            result = self.influx_client.query(
                query,
                self.args['database'],
                self.args['epoch'],
            )

            # top-level error.
            if 'error' in result:
                print_formatted_text(FormattedText([
                    ('ansibrightred', '[ERROR] '),
                ]),
                                     end='')
                print(result['error'])
                continue

            arr = json_to_tabular_result(result)
            print_formatted_text(FormattedText(arr))
Пример #31
0
def start_repl(p, prompt=' >> '):
    save_last = '_'  # XXX A little hacky

    p.set_output_format('rich')

    console = rich.console.Console()
    console.print(
        f"[purple]Preql {__version__} interactive prompt. Type help() for help[/purple]"
    )

    try:
        session = PromptSession(
            lexer=PygmentsLexer(GoLexer),
            completer=Autocompleter(p.interp.state),
            # key_bindings=kb
            validator=MyValidator(),
        )

        @Condition
        def multiline_filter():
            text = get_app().layout.get_buffer_by_name('DEFAULT_BUFFER').text
            return not _code_is_valid(text)

        while True:
            # Read
            try:
                code = session.prompt(prompt, multiline=multiline_filter)
                if not code.strip():
                    continue

                start_time = time()
                try:
                    if code == '.':
                        console.print(table_more(p.interp.state),
                                      overflow='ellipsis')
                        continue

                    # Evaluate (Really just compile)
                    res = p._run_code(code, '<repl>')

                    # Print
                    if res is not None and res is not objects.null:
                        assert isinstance(res, Object), (res, type(res))

                        if save_last:
                            p.interp.set_var(save_last, res)

                        res = res.repr(p.interp.state)
                        # repl_log.info(res)
                        if isinstance(res, str):
                            if len(res) > 200:
                                res = res[:100] + "..." + res[
                                    -100:]  # smarter limit?
                            res = rich.markup.escape(res)
                        console.print(res, overflow='ellipsis')

                except Signal as s:
                    for is_rich, line in s.get_rich_lines():
                        if is_rich:
                            rich.print(line)
                        else:
                            print(line)
                    # repl_log.error(s)
                    # p.interp.set_var('_e', objects.ExceptionInstance(e))
                    continue
                except ExitInterp as e:
                    return
                except Exception as e:
                    repl_log.exception(e)
                    raise
                    # continue

                duration = time() - start_time
                if duration > 1:
                    repl_log.info("(Query took %.2f seconds)" % duration)

            except KeyboardInterrupt:
                repl_log.info("Interrupted (Ctrl+C)")

    except (KeyboardInterrupt, EOFError):
        repl_log.info('Exiting Preql interaction')
Пример #32
0
    def run_cli(self):
        iterations = 0
        sqlexecute = self.sqlexecute
        logger = self.logger
        self.configure_pager()
        self.refresh_completions()

        history_file = config_location() + "history"
        if dir_path_exists(history_file):
            history = FileHistory(history_file)
        else:
            history = None
            self.echo(
                'Error: Unable to open the history file "{}". '
                "Your query history will not be saved.".format(history_file),
                err=True,
                fg="red",
            )

        key_bindings = cli_bindings(self)

        if not self.less_chatty:
            print("Version:", __version__)
            print(
                "Mail: https://groups.google.com/forum/#!forum/litecli-users")
            print("Github: https://github.com/dbcli/litecli")
            # print("Home: https://litecli.com")

        def get_message():
            prompt = self.get_prompt(self.prompt_format)
            if (self.prompt_format == self.default_prompt
                    and len(prompt) > self.max_len_prompt):
                prompt = self.get_prompt("\\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 iterations < 2

        def one_iteration(text=None):
            if text is None:
                try:
                    text = self.prompt_app.prompt()
                except KeyboardInterrupt:
                    return

                special.set_expanded_output(False)

                try:
                    text = self.handle_editor_command(text)
                except RuntimeError as e:
                    logger.error("sql: %r, error: %r", text, e)
                    logger.error("traceback: %r", traceback.format_exc())
                    self.echo(str(e), err=True, fg="red")
                    return

            if not text.strip():
                return

            if self.destructive_warning:
                destroy = confirm_destructive_query(text)
                if destroy is None:
                    pass  # Query was not destructive. Nothing to do here.
                elif destroy is True:
                    self.echo("Your call!")
                else:
                    self.echo("Wise choice!")
                    return

            # Keep track of whether or not the query is mutating. In case
            # of a multi-statement query, the overall query is considered
            # mutating if any one of the component statements is mutating
            mutating = False

            try:
                logger.debug("sql: %r", text)

                special.write_tee(self.get_prompt(self.prompt_format) + text)
                if self.logfile:
                    self.logfile.write("\n# %s\n" % datetime.now())
                    self.logfile.write(text)
                    self.logfile.write("\n")

                successful = False
                start = time()
                res = sqlexecute.run(text)
                self.formatter.query = text
                successful = True
                result_count = 0
                for title, cur, headers, status in res:
                    logger.debug("headers: %r", headers)
                    logger.debug("rows: %r", cur)
                    logger.debug("status: %r", status)
                    threshold = 1000
                    if is_select(status) and cur and cur.rowcount > threshold:
                        self.echo(
                            "The result set has more than {} rows.".format(
                                threshold),
                            fg="red",
                        )
                        if not confirm("Do you want to continue?"):
                            self.echo("Aborted!", err=True, fg="red")
                            break

                    if self.auto_vertical_output:
                        max_width = self.prompt_app.output.get_size().columns
                    else:
                        max_width = None

                    formatted = self.format_output(
                        title, cur, headers, special.is_expanded_output(),
                        max_width)

                    t = time() - start
                    try:
                        if result_count > 0:
                            self.echo("")
                        try:
                            self.output(formatted, status)
                        except KeyboardInterrupt:
                            pass
                        self.echo("Time: %0.03fs" % t)
                    except KeyboardInterrupt:
                        pass

                    start = time()
                    result_count += 1
                    mutating = mutating or is_mutating(status)
                special.unset_once_if_written()
            except EOFError as e:
                raise e
            except KeyboardInterrupt:
                # get last connection id
                connection_id_to_kill = sqlexecute.connection_id
                logger.debug("connection id to kill: %r",
                             connection_id_to_kill)
                # Restart connection to the database
                sqlexecute.connect()
                try:
                    for title, cur, headers, status in sqlexecute.run(
                            "kill %s" % connection_id_to_kill):
                        status_str = str(status).lower()
                        if status_str.find("ok") > -1:
                            logger.debug(
                                "cancelled query, connection id: %r, sql: %r",
                                connection_id_to_kill,
                                text,
                            )
                            self.echo("cancelled query", err=True, fg="red")
                except Exception as e:
                    self.echo(
                        "Encountered error while cancelling query: {}".format(
                            e),
                        err=True,
                        fg="red",
                    )
            except NotImplementedError:
                self.echo("Not Yet Implemented.", fg="yellow")
            except OperationalError as e:
                logger.debug("Exception: %r", e)
                if e.args[0] in (2003, 2006, 2013):
                    logger.debug("Attempting to reconnect.")
                    self.echo("Reconnecting...", fg="yellow")
                    try:
                        sqlexecute.connect()
                        logger.debug("Reconnected successfully.")
                        one_iteration(text)
                        return  # OK to just return, cuz the recursion call runs to the end.
                    except OperationalError as e:
                        logger.debug("Reconnect failed. e: %r", e)
                        self.echo(str(e), err=True, fg="red")
                        # If reconnection failed, don't proceed further.
                        return
                else:
                    logger.error("sql: %r, error: %r", text, e)
                    logger.error("traceback: %r", traceback.format_exc())
                    self.echo(str(e), err=True, fg="red")
            except Exception as e:
                logger.error("sql: %r, error: %r", text, e)
                logger.error("traceback: %r", traceback.format_exc())
                self.echo(str(e), err=True, fg="red")
            else:
                if is_dropping_database(text, self.sqlexecute.dbname):
                    self.sqlexecute.dbname = None
                    self.sqlexecute.connect()

                # Refresh the table names and column names if necessary.
                if need_completion_refresh(text):
                    self.refresh_completions(reset=need_completion_reset(text))
            finally:
                if self.logfile is False:
                    self.echo("Warning: This query was not logged.",
                              err=True,
                              fg="red")
            query = Query(text, successful, mutating)
            self.query_history.append(query)

        get_toolbar_tokens = create_toolbar_tokens_func(
            self, show_suggestion_tip)

        if self.wider_completion_menu:
            complete_style = CompleteStyle.MULTI_COLUMN
        else:
            complete_style = CompleteStyle.COLUMN

        with self._completer_lock:

            if self.key_bindings == "vi":
                editing_mode = EditingMode.VI
            else:
                editing_mode = EditingMode.EMACS

            self.prompt_app = PromptSession(
                lexer=PygmentsLexer(LiteCliLexer),
                reserve_space_for_menu=self.get_reserved_space(),
                message=get_message,
                prompt_continuation=get_continuation,
                bottom_toolbar=get_toolbar_tokens,
                complete_style=complete_style,
                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,
                enable_suspend=True,
                editing_mode=editing_mode,
                search_ignore_case=True,
            )

        try:
            while True:
                one_iteration()
                iterations += 1
        except EOFError:
            special.close_tee()
            if not self.less_chatty:
                self.echo("Goodbye!")
Пример #33
0
def create_readline():
    # create bindings
    # We handle ' ' (to right-align line numbers and indent), Backspace (to unalign and unindent), and Esc
    bindings = KeyBindings()

    @bindings.add('escape')
    def _(event):
        # TODO: somehow user must press Esc twice; not optimal
        b = event.current_buffer
        b.transform_current_line(lambda _: "")

    @bindings.add(' ')
    def _(event):
        global program
        p = re.compile('^( *)([0-9]+)$')
        b = event.current_buffer
        m = p.match(b.text)
        if m:  # TODO: check if we are at line end --  space after line number
            space, no_str = m.groups()
            spaces_needed = 6 - len(space) - len(no_str)
            if spaces_needed > 0:
                b.delete_before_cursor(len(no_str))
                b.insert_text(' ' * spaces_needed + no_str, overwrite=True)
            b.insert_text(' ')  # insert the actual space
            # if line exists then bring it into the editor
            no = int(no_str)
            line = program.try_get(no)
            if line:
                b.insert_text(line, move_cursor=False)
            # else if it does not exist, then check the previous line and indent
            else:
                prev_no = program.line_no_before(no)
                indent = TheProgram.determine_indent(prev_no
                                                     and program.get(prev_no))
                b.insert_text(' ' * indent)
        else:
            b.insert_text(' ')  # regular space

    @bindings.add('c-h')
    def _(event):
        p = re.compile('^( *)([0-9]+) $')
        b = event.current_buffer
        m = p.match(b.text)
        if m and len(
                b.text
        ) == 7:  # DEL right after line number: undo leading spaces, so one can type expressions
            space, no_str = m.groups()
            b.delete_before_cursor(len(b.text))  # delete all
            b.insert_text(no_str)  # reinsert plain number
        else:
            # delete indentation
            if b.text.endswith('    '):
                b.delete_before_cursor(4)  # unindent
            else:
                b.delete_before_cursor(1)

    # create lexer for syntax highlighting
    lexer = PygmentsLexer(Python3Lexer)

    # create PromptSession. This is the line editor.
    prompt_session = prompt_toolkit.PromptSession(key_bindings=bindings,
                                                  history=InMemoryHistory(),
                                                  lexer=lexer)

    # this is the getline() function we return
    def readline(default, pos):
        return prompt_session.prompt(default=default)

    return readline
Пример #34
0
def get_statusbar_text():
    return ' Press Ctrl-C to open menu. '


def get_statusbar_right_text():
    return ' {}:{}  '.format(
        text_field.document.cursor_position_row + 1,
        text_field.document.cursor_position_col + 1)


search_toolbar = SearchToolbar()
text_field = TextArea(
    lexer=DynamicLexer(
        lambda: PygmentsLexer.from_filename(
            ApplicationState.current_path or '.txt',
            sync_from_start=False)),
    scrollbar=True,
    line_numbers=True,
    search_field=search_toolbar,
)


class TextInputDialog(object):
    def __init__(self, title='', label_text='', completer=None):
        self.future = Future()

        def accept_text(buf):
            get_app().layout.focus(ok_button)
            buf.complete_state = None
            return True