Skip to content

Cần cấp chỗ cho menu gợi ý chỉ khi có completion, thay vì giữ chỗ cố định #6

Description

@damphat

Tóm tắt ý đồ

Làm app TUI inline bằng prompt_toolkit có ô nhập + gợi ý, nhưng:

  • Mặc định prompt_toolkit luôn giữ sẵn khoảng trống dưới prompt để vẽ menu → nhìn thừa khi chưa cần.
  • Đặt reserve_space_for_menu=0 thì hết chỗ trống, nhưng khi con trỏ ở cuối terminal menu bị cắt và biến mất.

Mong muốn: không giữ chỗ thường trực, chỉ tạo chỗ đúng lúc menu sắp hiện, xong thì thu lại — giống hành vi của bash/zsh.

Vì sao mặc định không làm được

  • reserve_space_for_menu > 0 → giữ chỗ cố định (tránh nháy).
  • = 0 → vẽ menu dạng float, không xin thêm dòng → ở đáy màn hình là hết chỗ vẽ.
  • prompt_toolkit không có tham số "tự động giữ chỗ khi cần".

Giải pháp

Dùng filter có sẵn has_completions để mở một container trống chỉ khi completer có kết quả.

from prompt_toolkit.application import Application
from prompt_toolkit.layout import (
    Layout, HSplit, Window, ConditionalContainer,
    FloatContainer, Float
)
from prompt_toolkit.widgets import TextArea
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.filters import has_completions
from prompt_toolkit.layout.menus import CompletionsMenu

completer = WordCompleter(['git status', 'git commit', 'docker ps'], ignore_case=True)

input_field = TextArea(
    height=1,
    prompt='> ',
    multiline=False,
    completer=completer,
    complete_while_typing=True,
)

menu = CompletionsMenu(max_height=8)

# chỗ trống chỉ xuất hiện khi có suggestion
reserve = ConditionalContainer(
    Window(height=8),
    filter=has_completions
)

root = FloatContainer(
    content=HSplit([input_field, reserve]),
    floats=[Float(xcursor=True, ycursor=True, content=menu)]
)

app = Application(
    layout=Layout(root, focused_element=input_field),
    full_screen=False
)

app.run()

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions