Пример #1
0
def _hl_text(nvim: Nvim, text: str) -> None:
    nvim.funcs.setreg("/", _magic_escape(text))

    def cont() -> None:
        nvim.options["hlsearch"] = True

    go(nvim, aw=async_call(nvim, cont))
Пример #2
0
        async def c0(s: State, manual: bool) -> None:
            with with_suppress(), timeit("**OVERALL**"):
                if lock.locked():
                    log.warn("%s", "SHOULD NOT BE LOCKED <><> OODA")
                async with lock:
                    ctx = await async_call(
                        nvim,
                        lambda: context(
                            nvim,
                            db=stack.bdb,
                            options=stack.settings.match,
                            state=s,
                            manual=manual,
                        ),
                    )
                    should = _should_cont(s, prev=s.context,
                                          cur=ctx) if ctx else False
                    _, col = ctx.position

                    if should:
                        state(context=ctx)
                        await stack.supervisor.interrupt()
                        metrics, _ = await gather(
                            stack.supervisor.collect(ctx),
                            async_call(
                                nvim,
                                lambda: complete(
                                    nvim, stack=stack, col=col, comps=()),
                            ) if stack.settings.display.pum.fast_close else
                            sleep(0),
                        )
                        s = state()
                        if s.change_id == ctx.change_id:
                            vim_comps = tuple(
                                trans(
                                    stack,
                                    pum_width=s.pum_width,
                                    context=ctx,
                                    metrics=metrics,
                                ))
                            await async_call(
                                nvim,
                                lambda: complete(nvim,
                                                 stack=stack,
                                                 col=col,
                                                 comps=vim_comps),
                            )
                    else:
                        await async_call(
                            nvim, lambda: complete(
                                nvim, stack=stack, col=col, comps=()))
                        state(inserted_pos=(-1, -1))
Пример #3
0
def _when_idle(nvim: Nvim, stack: Stack) -> None:
    global _HANDLE
    if _HANDLE:
        _HANDLE.cancel()

    def cont() -> None:
        buf = cur_buf(nvim)
        buf_type: str = buf_get_option(nvim, buf=buf, key="buftype")
        if buf_type == "terminal":
            nvim.api.buf_detach(buf)
            state(nono_bufs={buf.number})

        _insert_enter(nvim, stack=stack)
        stack.supervisor.notify_idle()

    get_running_loop().call_later(
        stack.settings.limits.idle_timeout,
        lambda: go(nvim, aw=async_call(nvim, cont)),
    )
Пример #4
0
async def _run(nvim: Nvim, ctx: BufContext, attrs: Iterable[FmtAttrs],
               cwd: str) -> None:
    body = linesep.join(ctx.lines).encode()
    path = Path(ctx.filename)
    with make_temp(path) as temp:
        temp.write_bytes(body)
        errs = [
            err async for err in aiterify(
                _fmt_output(attr, ctx=ctx, cwd=cwd, temp=temp)
                for attr in attrs) if err
        ]
        errors = (linesep * 2).join(errs)
        if errors:
            await gather(
                awrite(nvim, LANG("prettier failed")),
                set_preview_content(nvim, text=errors),
            )
        else:

            def cont() -> None:
                def it() -> Iterator[Tuple[Window, Tuple[int, int]]]:
                    wins = list_wins(nvim)
                    for win in wins:
                        buf = win_get_buf(nvim, win=win)
                        if buf == ctx.buf:
                            row, col = win_get_cursor(nvim, win)
                            yield win, (row, col)

                saved = {win: pos for win, pos in it()}

                lines = temp.read_text().splitlines()
                buf_set_lines(nvim, buf=ctx.buf, lo=0, hi=-1, lines=lines)

                for win, (row, col) in saved.items():
                    new_row = min(row, len(lines) - 1)
                    win_set_cursor(nvim, win=win, row=new_row, col=col)

            prettiers = LANG("step join sep").join(attr.bin for attr in attrs)
            nice = LANG("prettier succeeded", prettiers=prettiers)
            await gather(awrite(nvim, nice), async_call(nvim, cont))
Пример #5
0
 def cont() -> None:
     go(async_call(nvim, nvim.command, "silent! wa!"))
Пример #6
0
 async def cont() -> None:
     async for _ in aticker(3, immediately=False):
         go(async_call(nvim, check))
Пример #7
0
def _op_rg(nvim: Nvim, visual: VisualTypes) -> None:
    text = _hl_selected(nvim, visual=visual)
    escaped = escape(text).replace(r"\ ", " ")
    cont = lambda: nvim.command(f"Rg {escaped}")
    go(nvim, aw=async_call(nvim, cont))
Пример #8
0
def _op_fzf(nvim: Nvim, visual: VisualTypes) -> None:
    text = _hl_selected(nvim, visual=visual)
    cont = lambda: nvim.command(f"BLines {text}")
    go(nvim, aw=async_call(nvim, cont))
Пример #9
0
def _op_rg(nvim: Nvim, visual: VisualTypes = None) -> None:
    text = _hl_selected(nvim, visual=visual)
    cont = lambda: nvim.command(f"Rg {text}")
    go(async_call(nvim, cont))
Пример #10
0
 def cont() -> None:
     new_col = col + len(lhs.encode())
     nvim.api.set_vvar("char", lhs + cast(str, rhs))
     set_cur = lambda: win_set_cursor(
         nvim, win=win, row=row, col=new_col)
     go(async_call(nvim, set_cur))
Пример #11
0
async def _slurp(nvim: Nvim, stack: Stack,
                 warn: AbstractSet[SnippetWarnings]) -> None:
    with timeit("LOAD SNIPS"):
        (
            cwd,
            bundled,
            (user_compiled, user_compiled_mtimes),
            (_, user_snips_mtimes),
            mtimes,
        ) = await gather(
            async_call(nvim, get_cwd, nvim),
            _bundled_mtimes(nvim),
            _load_user_compiled(stack.supervisor.vars_dir),
            user_mtimes(nvim,
                        user_path=stack.settings.clients.snippets.user_path),
            stack.sdb.mtimes(),
        )

        stale = mtimes.keys() - (bundled.keys() | user_compiled.keys())
        compiled = {
            path: mtime
            for path, mtime in chain(bundled.items(), user_compiled.items())
            if mtime > mtimes.get(path, -inf)
        }
        new_user_snips = {
            fmt_path(cwd, path=path, is_dir=False): (
                datetime.fromtimestamp(mtime).strftime(
                    stack.settings.display.time_fmt),
                datetime.fromtimestamp(prev).strftime(
                    stack.settings.display.time_fmt) if
                (prev := user_compiled_mtimes.get(path)) else "??",
            )
            for path, mtime in user_snips_mtimes.items()
            if mtime > user_compiled_mtimes.get(path, -inf)
        }

        await stack.sdb.clean(stale)
        if SnippetWarnings.missing in warn and not (bundled or user_compiled):
            await sleep(0)
            await awrite(nvim, LANG("fs snip load empty"))

        for fut in as_completed(
                tuple(
                    _load_compiled(path, mtime)
                    for path, mtime in compiled.items())):
            try:
                path, mtime, loaded = await fut
            except (OSError, JSONDecodeError, DecodeError) as e:
                tpl = """
                Failed to load compiled snips
                ${e}
                """.rstrip()
                log.warn("%s", Template(dedent(tpl)).substitute(e=type(e)))
            else:
                await stack.sdb.populate(path, mtime=mtime, loaded=loaded)
                await awrite(
                    nvim,
                    LANG(
                        "fs snip load succ",
                        path=fmt_path(cwd, path=path, is_dir=False),
                    ),
                )

        if SnippetWarnings.outdated in warn and new_user_snips:
            paths = linesep.join(f"{path} -- {prev} -> {cur}"
                                 for path, (cur,
                                            prev) in new_user_snips.items())
            await awrite(nvim, LANG("fs snip needs compile", paths=paths))


@rpc(blocking=True)
def _load_snips(nvim: Nvim, stack: Stack) -> None:
    go(nvim,
       aw=_slurp(nvim, stack=stack, warn=stack.settings.clients.snippets.warn))


atomic.exec_lua(f"{NAMESPACE}.{_load_snips.name}()", ())


def compile_one(
    stack: Stack,
    grammar: SnippetGrammar,
    path: PurePath,
    info: ParseInfo,
    lines: Iterable[Tuple[int, str]],
) -> Compiled:
    filetype, exts, snips = load_neosnippet(grammar, path=path, lines=lines)
    parsed = tuple(
        _trans(
            stack.settings.match.unifying_chars,
            smart=stack.settings.completion.smart,
            info=info,
            snips=snips,
        ))

    compiled = Compiled(
        path=path,
        filetype=filetype,
        exts=exts,
        parsed=parsed,
    )
    return compiled


async def compile_user_snippets(nvim: Nvim, stack: Stack) -> None:
    with timeit("COMPILE SNIPS"):
        info = ParseInfo(visual="", clipboard="", comment_str=("", ""))
        _, mtimes = await user_mtimes(
            nvim, user_path=stack.settings.clients.snippets.user_path)
        loaded = await to_thread(lambda: load_direct(
            False,
            lsp=(),
            neosnippet=mtimes,
            ultisnip=(),
            neosnippet_grammar=SnippetGrammar.lsp,
        ))
        _ = tuple(
            _trans(
                stack.settings.match.unifying_chars,
                smart=stack.settings.completion.smart,
                info=info,
                snips=loaded.snippets.values(),
            ))
        try:
            await _dump_compiled(stack.supervisor.vars_dir,
                                 mtimes=mtimes,
                                 loaded=loaded)
        except OSError as e:
            await awrite(nvim, e)
        else:
            await _slurp(nvim, stack=stack, warn={SnippetWarnings.missing})