Exemple #1
0
def _ex(vim: Nvim, word: str) -> None:
    # NOTE:
    # <C-b> (\x02) in a command-line move the caret to the beginning.
    # Somehow the key above works in 'input()' function as well.
    expr = vim.call('input', ':', ' %s\x02' % word, 'command')
    if expr:
        vim.command(expr)
Exemple #2
0
def show_file(nvim: Nvim, *, state: State, settings: Settings,
              click_type: ClickType) -> None:
    path = state.current
    hold = click_type == ClickType.secondary
    if click_type == ClickType.tertiary:
        nvim.api.command("tabnew")
    if path:
        with HoldWindowPosition(nvim, hold=hold):
            non_fm_windows = tuple(find_non_fm_windows_in_tab(nvim))
            buffer: Optional[Buffer] = next(
                find_buffer_with_file(nvim, file=path), None)
            window: Window = next(
                find_window_with_file_in_tab(nvim, file=path),
                None) or next(iter(non_fm_windows), None) or new_window(
                    nvim, open_left=not settings.open_left, width=state.width)

            nvim.api.set_current_win(window)
            non_fm_count = len(non_fm_windows)
            if click_type == ClickType.v_split and non_fm_count:
                nvim.api.command("vsplit")
            elif click_type == ClickType.h_split and non_fm_count:
                nvim.api.command("split")
            window = nvim.api.get_current_win()

            if buffer is None:
                nvim.command(f"edit {path}")
            else:
                nvim.api.win_set_buf(window, buffer)
            resize_fm_windows(nvim, state.width)
            nvim.api.command("filetype detect")
Exemple #3
0
def kill_buffers(nvim: Nvim, paths: Iterable[str]) -> None:
    buffers: Sequence[Buffer] = nvim.api.list_bufs()
    for buffer in buffers:
        name = nvim.api.buf_get_name(buffer)
        if any(name == path or is_parent(parent=path, child=name)
               for path in paths):
            nvim.command(f"bwipeout! {buffer.number}")
Exemple #4
0
def test_delete(vim: Nvim) -> None:
    vim.command("edit text1")
    vim.command("split text2")
    vim.command("split text3")
    vim.command("tabnew")
    vim.command("edit text4")
    vim.command("split text5")
    vim.command("split text6")
    w = Window(vim)
    w.delete([
        {
            "action__tabnr": 1,
            "action__winnr": 1
        },  # text3
        {
            "action__tabnr": 1,
            "action__winnr": 2
        },  # text2
        {
            "action__tabnr": 2,
            "action__winnr": 1
        },  # text6
        {
            "action__tabnr": 2,
            "action__winnr": 2
        },  # text5
    ])
    assert vim.funcs.winnr("$") == 1
    assert Path(vim.tabpages[0].window.buffer.name).name == "text1"
    assert Path(vim.tabpages[1].window.buffer.name).name == "text4"
Exemple #5
0
def test_only(vim: Nvim) -> None:
    vim.command("edit text1")
    vim.command("split text2")
    vim.command("split text3")
    w = Window(vim)
    w.only({"action__tabnr": 1, "action__winnr": 1})  # text3
    assert vim.funcs.winnr("$") == 1
    assert Path(vim.current.buffer.name).name == "text3"
Exemple #6
0
def clearmatch(vim: Nvim) -> None:
    if not vim.call('exists', 'w:denite_match_id'):
        return

    # For async RPC error
    vim.command('silent! call matchdelete({})'.format(
        vim.current.window.vars['denite_match_id']))
    vim.command('silent! unlet w:denite_match_id')
Exemple #7
0
def _term_open(nvim: Nvim, prog: AnyPath, *args: AnyPath, opts: TermOpts = {}) -> None:
    buf = _ensure_marked_buf(nvim)
    buf_type: str = buf_get_option(nvim, buf=buf, key="buftype")
    is_term_buf = buf_type == "terminal"
    open_float_win(nvim, margin=0, relsize=0.95, buf=buf, border="rounded")
    if not is_term_buf:
        cmds = tuple(map(str, chain((which(prog),), args)))
        nvim.funcs.termopen(cmds, opts)
    nvim.command("startinsert")
Exemple #8
0
def _term_open(nvim: Nvim, *args: str, opts: TermOpts = {}) -> None:
    buf = _ensure_marked_buf(nvim)
    buf_type: str = buf_get_option(nvim, buf=buf, key="buftype")
    is_term_buf = buf_type == "terminal"
    open_float_win(nvim, margin=0, relsize=0.95, buf=buf)
    if not is_term_buf:
        cmds = args or (environ["SHELL"], )
        nvim.funcs.termopen(cmds, opts)
    nvim.command("startinsert")
Exemple #9
0
def _show_file(nvim: Nvim, *, state: State, settings: Settings,
               click_type: ClickType) -> None:
    if click_type is ClickType.tertiary:
        nvim.api.command("tabnew")
        win = cur_win(nvim)
        for key, val in settings.win_actual_opts.items():
            win_set_option(nvim, win=win, key=key, val=val)

    path = state.current
    if path:
        hold = click_type is ClickType.secondary
        mgr = hold_win_pos(nvim) if hold else nullcontext()
        with mgr:
            non_fm_windows = tuple(
                find_non_fm_windows_in_tab(nvim, last_used=state.window_order))
            buf = next(find_buffers_with_file(nvim, file=path), None)
            win = next(
                chain(
                    find_window_with_file_in_tab(
                        nvim, last_used=state.window_order, file=path),
                    non_fm_windows,
                ),
                None,
            ) or new_window(
                nvim,
                last_used=state.window_order,
                win_local=settings.win_actual_opts,
                open_left=not settings.open_left,
                width=None if len(non_fm_windows) else
                nvim.options["columns"] - state.width - 1,
            )

            set_cur_win(nvim, win=win)
            non_fm_count = len(non_fm_windows)

            if click_type is ClickType.v_split and non_fm_count:
                nvim.api.command("vnew")
                temp_buf = cur_buf(nvim)
                buf_set_option(nvim, buf=temp_buf, key="bufhidden", val="wipe")
            elif click_type is ClickType.h_split and non_fm_count:
                nvim.api.command("new")
                temp_buf = cur_buf(nvim)
                buf_set_option(nvim, buf=temp_buf, key="bufhidden", val="wipe")

            win = cur_win(nvim)

            if buf is None:
                escaped = nvim.funcs.fnameescape(normcase(path))
                nvim.command(f"edit! {escaped}")
            else:
                win_set_buf(nvim, win=win, buf=buf)

            resize_fm_windows(nvim,
                              last_used=state.window_order,
                              width=state.width)
            nvim.api.command("filetype detect")
Exemple #10
0
def test_jump(vim: Nvim) -> None:
    vim.command("edit text1")
    vim.command("split text2")
    vim.command("split text3")
    vim.command("tabnew")
    vim.command("edit text4")
    vim.command("split text5")
    vim.command("split text6")
    w = Window(vim)
    w.jump({"action__tabnr": 1, "action__winnr": 3})  # text1
    assert Path(vim.current.buffer.name).name == "text1"
Exemple #11
0
def test_open(vim: Nvim) -> None:
    vim.command("edit text1")
    vim.command("split text2")
    vim.command("split text3")
    w = Window(vim)
    w.open({"action__tabnr": 1, "action__winnr": 3})  # text1
    assert [Path(x.buffer.name).name for x in vim.windows] == [
        "text1",
        "text2",
        "text1",
    ]
Exemple #12
0
def new_window(nvim: Nvim, *, open_left: bool, width: int) -> Window:
    split_r = nvim.api.get_option("splitright")

    windows: Sequence[Window] = tuple(w for w in find_windows_in_tab(nvim))
    focus_win = windows[0] if open_left else windows[-1]
    direction = False if open_left else True

    nvim.api.set_option("splitright", direction)
    nvim.api.set_current_win(focus_win)
    nvim.command(F"{width}vnew")
    nvim.api.set_option("splitright", split_r)

    window: Window = nvim.api.get_current_win()
    return window
Exemple #13
0
def _paste(vim: Nvim, word: str, command: str, regtype: str) -> None:
    if regtype == '':
        regtype = 'v'

    # Paste.
    old_reg = [vim.call('getreg', '"'), vim.call('getregtype', '"')]

    vim.call('setreg', '"', word, regtype)
    try:
        vim.command('normal! ""' + command)
    finally:
        vim.call('setreg', '"', old_reg[0], old_reg[1])

    # Open folds
    vim.command('normal! zv')
Exemple #14
0
def _show_file(
    nvim: Nvim, *, state: State, settings: Settings, click_type: ClickType
) -> None:
    if click_type is ClickType.tertiary:
        nvim.api.command("tabnew")

    path = state.current
    if path:
        hold = click_type is ClickType.secondary
        mgr = hold_win_pos(nvim) if hold else nullcontext()
        with mgr:
            non_fm_windows = tuple(find_non_fm_windows_in_tab(nvim))
            buf = next(find_buffers_with_file(nvim, file=path), None)
            win = next(
                chain(
                    find_window_with_file_in_tab(nvim, file=path),
                    (win for win in non_fm_windows if _win_nochange(nvim, win=win)),
                ),
                None,
            ) or new_window(
                nvim,
                open_left=not settings.open_left,
                width=None
                if len(non_fm_windows)
                else nvim.options["columns"] - state.width - 1,
            )

            set_cur_win(nvim, win=win)
            non_fm_count = len(non_fm_windows)

            if click_type is ClickType.v_split and non_fm_count:
                nvim.api.command("vnew")
                temp_buf = cur_buf(nvim)
                buf_set_option(nvim, buf=temp_buf, key="bufhidden", val="wipe")
            elif click_type is ClickType.h_split and non_fm_count:
                nvim.api.command("new")
                temp_buf = cur_buf(nvim)
                buf_set_option(nvim, buf=temp_buf, key="bufhidden", val="wipe")

            win = cur_win(nvim)

            if buf is None:
                nvim.command(f"edit {path}")
            else:
                win_set_buf(nvim, win=win, buf=buf)

            resize_fm_windows(nvim, state.width)
            nvim.api.command("filetype detect")
Exemple #15
0
def cwd_input(vim: Nvim, cwd: str, prompt: str,
              text: str = '', completion: str = '') -> typing.Optional[Path]:
    """
    Returns the absolute input path in cwd.
    """
    save_cwd = vim.call('getcwd')
    vim.command(f'silent lcd {cwd}')

    filename: str = vim.call('input', prompt, text, completion)

    vim.command(f'silent lcd {save_cwd}')

    if not filename:
        return None

    return Path(cwd).joinpath(filename).resolve()
Exemple #16
0
def _change_dir(nvim: Nvim, state: State, settings: Settings,
                is_visual: bool) -> Optional[Stage]:
    """
    Change root directory
    """

    node = next(indices(nvim, state=state, is_visual=is_visual), None)
    if not node:
        return None
    else:
        cwd = node.path if is_dir(node) else dirname(node.path)
        new_state = new_root(nvim, state=state, settings=settings, new_cwd=cwd)
        focus = new_state.root.path
        nvim.command(f"chdir {focus}")
        write(nvim, LANG("new cwd", cwd=focus))
        return Stage(new_state, focus=focus)
Exemple #17
0
def echoerr(vim: Nvim, msg: str, label: str = "") -> None:
    """Vim echoerr."""
    vim.command("echohl ErrorMsg")
    label_expr = ""
    if label:
        label_expr = "[{}]: ".format(label)
    vim.command('echomsg "{}{}"'.format(label_expr, msg))
    vim.command("echohl None")
Exemple #18
0
def clear_cmdline(vim: Nvim) -> None:
    vim.command('redraw | echo')
Exemple #19
0
def make_diary(
    nvim: Nvim,
    options: PluginOptions,
    gcal_service: SimpleNvimGoogleCal,
    github_service: SimpleNvimGithub,
    auto_command: bool = False,
) -> None:
    """make_diary

    Make the actual diary markdown file.
    This includes the following steps:
        * Open the file if it already exists.
        * If not, put the default template in and save.
    """

    # If the buffer is not empty, don't continue. Issue an error if manually
    # called, don't issue an error for an autocommand.
    if not is_buffer_empty(nvim):
        if not auto_command:
            nvim.err_write("Buffer is not empty, can't create diary.\n")
        return

    # If options is none, then everything else probably wasn't setup either.
    if options is None:
        nvim.err_write("Options weren't initialised, aborting.\n")
        return

    full_markdown: List[str] = []

    diary_date: str = get_diary_date(nvim)
    diary_metadata: Dict[str, str] = {"Date": diary_date}

    full_markdown.extend(generate_markdown_metadata(diary_metadata))
    set_buffer_contents(nvim, full_markdown)

    for heading in options.daily_headings:
        full_markdown.append(f"## {heading}")
        full_markdown.append("")
    set_buffer_contents(nvim, full_markdown)

    # Add in issues section
    issues: List[GitHubIssue] = []
    if options.use_github_repo and github_service and github_service.active:
        issues = github_service.active_issues

    issue_markdown: List[str] = produce_issue_markdown(options, issues)
    full_markdown.extend(issue_markdown)
    set_buffer_contents(nvim, full_markdown)

    # Add in the calendar entries
    days_events: List[CalendarEvent] = []
    if options.use_google_calendar and gcal_service and gcal_service.active:
        date_today_object: date = parser.parse(diary_date).date()
        if date_today_object == date.today():
            days_events = gcal_service.active_events
        else:
            days_events = gcal_service.get_events_for_date(date_today_object)

    schedule_markdown: List[str] = produce_schedule_markdown(days_events)
    full_markdown.extend(schedule_markdown)

    # Set the buffer contents and save the file.
    set_buffer_contents(nvim, full_markdown)
    nvim.command(":w")

    if options.auto_generate_diary_index:
        generate_diary_index(options)
Exemple #20
0
def _bigger_preview(nvim: Nvim, stack: Stack,
                    args: Tuple[str, Sequence[str]]) -> None:
    syntax, lines = args
    nvim.command("stopinsert")
    set_preview(nvim, syntax=syntax, preview=lines)
Exemple #21
0
def echomsg(vim: Nvim, msg: str, label: str = "") -> None:
    """Vim echomsg."""
    label_expr = ""
    if label:
        label_expr = "[{}]:".format(label)
    vim.command('echomsg "{}{}"'.format(label_expr, msg))
Exemple #22
0
def test_get_all_windows(vim: Nvim) -> None:
    vim.command("edit text1")
    vim.command("split text2")
    vim.command("split text3")
    vim.command("split text4")
    vim.command("tabnew")
    vim.command("edit text5")
    vim.command("split text6")
    vim.command("split text7")
    vim.command("split text8")
    vim.command("tabnext")
    w = Window(vim)
    for c in [
        {
            "no_current":
            False,
            "expected": [
                [
                    "text4",
                    "1: [1/4] % text4",
                    1,
                    1,
                ],
                [
                    "text3",
                    "1: [2/4] # text3",
                    1,
                    2,
                ],
                [
                    "text2",
                    "1: [3/4]   text2",
                    1,
                    3,
                ],
                [
                    "text1",
                    "1: [4/4] $ text1",
                    1,
                    4,
                ],
                [
                    "text8",
                    "2: [1/4]   text8",
                    2,
                    1,
                ],
                [
                    "text7",
                    "2: [2/4]   text7",
                    2,
                    2,
                ],
                [
                    "text6",
                    "2: [3/4]   text6",
                    2,
                    3,
                ],
                [
                    "text5",
                    "2: [4/4]   text5",
                    2,
                    4,
                ],
            ],
        },
        {
            "no_current":
            True,
            "expected": [
                [
                    "text3",
                    "1: [2/4] # text3",
                    1,
                    2,
                ],
                [
                    "text2",
                    "1: [3/4]   text2",
                    1,
                    3,
                ],
                [
                    "text1",
                    "1: [4/4] $ text1",
                    1,
                    4,
                ],
                [
                    "text8",
                    "2: [1/4]   text8",
                    2,
                    1,
                ],
                [
                    "text7",
                    "2: [2/4]   text7",
                    2,
                    2,
                ],
                [
                    "text6",
                    "2: [3/4]   text6",
                    2,
                    3,
                ],
                [
                    "text5",
                    "2: [4/4]   text5",
                    2,
                    4,
                ],
            ],
        },
    ]:
        expected = [{
            "word": x[0],
            "abbr": x[1],
            "action__tabnr": x[2],
            "action__winnr": x[3]
        } for x in cast(List[Any], c["expected"])]
        assert expected == w.get_all_windows(c["no_current"])