Skip to content
Aditya Bhalsod
← AI
AIBeginner

Triggering Gemini From Any Window With a Global Keyboard Listener

How twoslash-alternative turns global keystrokes into Gemini requests with pynput, pastes answers back via the clipboard, and what such a key listener sees and sends.

  • #python
  • #pynput
  • #gemini
  • #clipboard
Contents
  1. Turning keystrokes into a trigger
  2. What the listener keeps and sends
  3. Pasting the answer back
  4. Telling code from text
  5. When this approach fits

twoslash-alternative is one Python script, twoslash_alternative.py. While it runs, typing >>your prompt<< in any window sends your prompt to Google Gemini and pastes the answer into the window you are typing in. The README describes it as inspired by twoslash and as an evaluation project, not production ready.

It is a small program with an unusually sensitive input: a keyboard hook that sees every key. So this post covers how it works, and plainly what it does with what it sees.

Turning keystrokes into a trigger

pynput gives the script a global listener: keyboard.Listener(on_press=on_press) calls on_press for every key press, whichever window has focus. The callback keeps one module-level string, captured_text, and appends to it.

Python
if hasattr(key, "char"):
    captured_text += key.char
elif key == keyboard.Key.space:
    captured_text += " "
elif key == keyboard.Key.backspace:
    captured_text = captured_text[:-1]

if PATTERN_START in captured_text and captured_text.endswith(PATTERN_END):
    matches = re.findall(r">>(.*?)<<", captured_text, re.DOTALL)
    extracted_text = "".join(matches)
    captured_text = ""

After every key, the check asks two things: does the buffer contain >> somewhere, and does it end with <<? The trigger fires on the second <, so no Enter key is involved. The regex is non-greedy and uses re.DOTALL, so a prompt can span several lines, and each pair of markers gives one match. The matches are joined into a single prompt.

What the listener keeps and sends

Key eventWhat the code does
Printable keyAppends the character to the buffer
Space, Enter, TabAppends a space, a newline or a tab
BackspaceRemoves the last character
Other keys such as Shift or arrowsNothing, the buffer stays as it is
EscStops the listener
Markers matchedPrints the buffer to the console, then empties it

The buffer lives in memory. The script never writes it to a file, and the only network client it imports is google-genai. But the buffer has no length limit and no timeout, and it does not know which window has focus or whether a field is a password field. Everything typed since the last match sits in it.

That has a consequence. A stray >> earlier in the buffer, such as cin >> x; in a C++ editor, stays there. The next time the buffer ends in <<, for example when you type cout <<, everything from that stray >> to the first << is treated as the prompt. Running the same regex over that buffer returns x;\ncout, and that text would go to Gemini.

What is sent is a fixed instruction plus the extracted text, wrapped in triple backticks, through genai.Client(api_key=API_KEY). The key comes from GOOGLE_API_KEY in a .env file, and the repo ships .env.example with a placeholder.

Pasting the answer back

The reply comes back as text, so the script needs a way to put it into another application. It uses the clipboard plus simulated keys, run on a separate threading.Thread.

Python
def delayed_response(response):
    cleaned_text = "\n".join(
        line for line in str(response).splitlines() if "```" not in line
    )
    pyperclip.copy(cleaned_text)

    keyboard_controller.press(keyboard.Key.enter)
    keyboard_controller.release(keyboard.Key.enter)
    time.sleep(1)

    keyboard_controller.press(keyboard.Key.ctrl_l)
    keyboard_controller.press("v")
    keyboard_controller.release("v")
    keyboard_controller.release(keyboard.Key.ctrl_l)

First it drops any line containing triple backticks, which strips any Markdown fence the model emits anyway. Then it copies to the clipboard, presses Enter to open a new line, waits one second and sends Ctrl + V. The Gemini call itself is synchronous inside on_press; only the paste is threaded.

The gotchas are all visible in those lines. The typed >>prompt<< is never deleted. Your previous clipboard contents are overwritten and not restored. The paste is hard-coded to left Ctrl, with no branch for the Command key on macOS. The one-second wait is fixed, not a check that the window is ready.

Telling code from text

The script decides between two prompts by looking for keywords in what you typed.

Python
if any(
    [
        check in extracted_text.lower()
        for check in (
            "code", "python", "javascript", "java", "c++", "c#", "html",
            "css", "program", "script", "function", "class", "method",
            "variable", "object",
        )
        if check in extracted_text.lower()
    ]
):

If any keyword matches, the code prompt asks for raw code with no Markdown, and only comments for explanation. Otherwise the text prompt asks for structured text with no code. Both use the hard-coded model gemini-3.6-flash. The inner if repeats the outer test, so any(check in prompt for check in KEYWORDS) would do the same job.

The match is a substring test, not a word test. >>write a short description of my product<< takes the code branch because description contains script. objective contains object, and classic contains class.

When this approach fits

The README says not to use it for sensitive, private or regulated data, and I agree. As a demo of two mechanisms, a key buffer and clipboard paste, it is short and readable.

If I rebuilt it, I would start buffering only after seeing >>, clear it after a pause or a character limit, and match whole words, or let the user choose the mode in the prompt. Until then it fits a personal experiment on a machine where you accept what a global hook sees.

Found this useful? Share it with your team.

Keep reading

More from AI and beyond