#!/usr/bin/env python3
"""optmux-extract — optmux eXtract: text from a pane, typed back or copied.

Usage: optmux-extract [PANE_ID]   (meant to run in a tmux popup; the active pane by default)

Unlike extrakto, lines keep their screen order and duplicates (`fi`, `done`, blank lines, ...), so
a multiline script survives the round trip. `C-M-x` switches what is listed: lines, or spans (runs of text the
program itself styled: colored, bold, underlined, ...) mixed, in screen order, with patterns (URLs, paths, file
names, commit hashes, PR/issue numbers like #234, quoted text, versions). Enter types the selection into the pane; `C-y` copies it, by the method
`C-t` cycles through (OSC 52, the system clipboard, or just the tmux buffer). The last filter and copy
method are remembered (tmux options on the server) for the next time, and so are each filter's query and the
item the cursor was on: it opens fresh, and `M-p` steps back through the filter's earlier queries (each with its
cursor), `M-n` forward again to a fresh start. `icons` (emoji, nerd or
text, as in optmux Find) says how a pattern's kind is drawn.

The selection can also be looked up in the project instead: `C-f` finds it among the files, `C-g` greps for it
and `C-M-f` searches everything (optmux Find, started in this same popup with the text as its query).
"""

import base64
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import textwrap
from dataclasses import dataclass

SGR = re.compile(r"\x1b\[([0-9;:]*)m")
# any other escape sequence (OSC 8 hyperlinks, cursor movement, ...) is noise for our purposes
OTHER_ESCAPES = re.compile(r"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;:?]*[A-Za-ln-z]|\x1b[()][A-Z0-9]")

# whatever is left after stripping escapes must not reach the pane: a stray ESC[201~ would end the
# bracketed paste early and run the rest as typed input
CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f]")

MIN_SPAN = 2  # characters; shorter styled runs are bullets, punctuation and the like


@dataclass(frozen=True)
class Style:
    fg: tuple = ()
    bg: tuple = ()
    attrs: frozenset = frozenset()  # SGR codes: 1 bold, 2 dim, 3 italic, 4 underline, 7 reverse, 9 strike

    @property
    def plain(self):
        return not (self.fg or self.bg or self.attrs)

    def sgr(self):
        """The escape sequence that switches to this style from a clean slate."""
        params = sorted(self.attrs) + [*self.fg, *self.bg]
        return "\x1b[0;" + ";".join(map(str, params)) + "m" if params else "\x1b[0m"


def apply_sgr(style, params):
    """Style after applying one SGR escape's parameters."""
    # colon sub-parameters: 38:2::R:G:B is 38;2;R;G;B, and 4:3 (a curly underline) is just underline
    params = re.sub(r"\b([34]8):2::", r"\1;2;", params)
    params = re.sub(r"(^|;)4:\d", r"\g<1>4", params)
    codes = [int(c) if c else 0 for c in re.split(r"[;:]", params)] if params else [0]
    fg, bg, attrs = style.fg, style.bg, set(style.attrs)
    i = 0
    while i < len(codes):
        c = codes[i]
        if c == 0:
            fg, bg, attrs = (), (), set()
        elif c in (1, 2, 3, 4, 7, 9):
            attrs.add(c)
        elif c == 22:
            attrs -= {1, 2}
        elif c in (23, 24, 27, 29):
            attrs.discard(c - 20)
        elif 30 <= c <= 37 or 90 <= c <= 97:
            fg = (c,)
        elif c == 39:
            fg = ()
        elif 40 <= c <= 47 or 100 <= c <= 107:
            bg = (c,)
        elif c == 49:
            bg = ()
        elif c in (38, 48):
            n = {5: 3, 2: 5}.get(codes[i + 1] if i + 1 < len(codes) else None)  # 38;5;N or 38;2;R;G;B
            if n is None:
                break
            color = tuple(codes[i : i + n])
            fg, bg = (color, bg) if c == 38 else (fg, color)
            i += n - 1
        i += 1
    return Style(fg, bg, frozenset(attrs))


def parse_line(raw):
    """(plain text, [(start, end, Style)]) for one captured line; spans cover non-default style runs."""
    raw = OTHER_ESCAPES.sub("", raw)
    plain, runs, style, start, pos = [], [], Style(), 0, 0
    for piece in re.split(r"(\x1b\[[0-9;:]*m)", raw):
        m = SGR.fullmatch(piece)
        if m:
            new = apply_sgr(style, m.group(1))
            if new != style:
                if not style.plain and pos > start:
                    runs.append((start, pos, style))
                style, start = new, pos
        else:
            piece = CONTROL_CHARS.sub("", piece)
            plain.append(piece)
            pos += len(piece)
    if not style.plain and pos > start:
        runs.append((start, pos, style))
    return "".join(plain), runs


FILTERS = ["lines", "spans"]
COPIERS = ["osc52", "native", "buffer"]
FILTER_OPTION = "@optmux-extract-filter"
COPY_OPTION = "@optmux-extract-copy"

# Well-known things worth copying. An earlier pattern claims its text first, so a path inside a URL
# is not listed again, and nothing overlaps within a line.
PATH_CHARS = r"[\w.@%+=,~-]"
PATTERNS = [
    ("url", r"\b[a-zA-Z][a-zA-Z0-9+.-]*://[^\s<>\"'`]+"),
    ("path", rf"(?<![\w/.~-])(?:~|\.{{1,2}})?/{PATH_CHARS}+(?:/{PATH_CHARS}+)*/?(?::\d+){{0,2}}"),  # /abs ~/home ./rel ../up
    ("path", rf"(?<![\w/.~-]){PATH_CHARS}+(?:/{PATH_CHARS}+)+/?(?::\d+){{0,2}}"),  # dir/with/slash
    ("hash", r"\b(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b"),  # git hashes: hex with digits and letters
    ("pr", r"(?<![\w&/#])#\d+\b"),  # PR/issue numbers: #234
    ("ver", r"\bv?\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?(?!\.?\d)"),  # semver (not 192.168.1.100)
    ("file", r"(?<![\w/.~-])[\w-]+(?:\.[\w-]+)*\.[A-Za-z][A-Za-z0-9]{0,7}(?:\.\d+)*\b(?::\d+){0,2}"),  # name.ext[:line[:col]], lib.so.6
    # quoted text: 'x' "x" `x` and GNU's `x' (help and man pages); the quotes are dropped. Last, so what is
    # recognizable inside (a path, a file) is listed as itself, and an apostrophe (don't) doesn't open one.
    ("quote", r"(?<!\w)(?:`(?=\S)([^`\n]+?)(?<=\S)[`']|'(?=\S)([^'\n]+?)(?<=\S)'|\"(?=\S)([^\"\n]+?)(?<=\S)\")(?!\w)"),
]
PATTERNS = [(label, re.compile(rx)) for label, rx in PATTERNS]
TRAILING_PUNCTUATION = ".,;:!?'\")]}>"
CLOSERS = {")": "(", "]": "[", "}": "{"}


def trim_url(text):
    """Drop sentence punctuation after a URL, but keep a closing bracket that balances an opening one."""
    while text and text[-1] in TRAILING_PUNCTUATION:
        if text[-1] in CLOSERS and text.count(text[-1]) <= text.count(CLOSERS[text[-1]]):
            break
        text = text[:-1]
    return text


# How each item is drawn, by `icons` (the same setting as optmux Find, whose glyphs these follow): a pattern by
# its kind, any other by the filter it is listed by (the same icon on every row, so switching filters keeps the columns).
PATTERN_ICONS = {
    "emoji": {"url": "🔗", "path": "📁", "file": "📄", "quote": "💬", "hash": "#️⃣", "pr": "🔀", "ver": "🏷️", "lines": "📃", "spans": "🎨"},
    "nerd": {"url": "\uf0c1", "path": "\uf07b", "file": "\uf016", "quote": "\uf10d", "hash": "\ue729", "pr": "\ue726", "ver": "\uf02b",
             "lines": "\uf0c9", "spans": "\uf1fc"},
    "none": {kind: "" for kind in ("url", "path", "file", "quote", "hash", "pr", "ver", "lines", "spans")},
    "text": {"url": "url ", "path": "path", "file": "file", "quote": "quot", "hash": "hash", "pr": "pr  ", "ver": "ver ", "lines": "line", "spans": "span"},
}


def icon_style():
    """`icons` (from the optmux config, $OPTMUX_DIR/find.json) or OPTMUX_ICONS; nerd by default."""
    style = os.environ.get("OPTMUX_ICONS")
    if style not in PATTERN_ICONS:
        try:
            style = json.loads(open(os.path.join(os.environ["OPTMUX_DIR"], "find.json")).read()).get("icons")
        except (KeyError, OSError, ValueError, AttributeError):
            style = None
    return style if style in PATTERN_ICONS else "nerd"


def find_patterns(plain):
    """[(start, label, text)] for the well-known patterns in a line, left to right, without overlaps."""
    taken, found = [], []
    for label, rx in PATTERNS:
        for m in rx.finditer(plain):
            if label == "quote":
                text, (s, e) = next(g for g in m.groups() if g is not None), m.span()
            else:
                text = trim_url(m.group()) if label == "url" else m.group().rstrip(".,")
                s, e = m.start(), m.start() + len(text)
            if text and not any(s < te and ts < e for ts, te in taken):
                taken.append((s, e))
                found.append((s, label, text))
    return sorted(found)


def span_items(parsed, width):
    """([(text, style, line, column)], covered) for the styled runs on the screen, `covered` being {line: [(start, end)]}. A run that fills its line right up to the edge and
    continues in the same style at the start of the next line was wrapped by the program: join the two.
    Only an exact fit counts (the next line's first word wouldn't have fitted), so that is precise but misses some."""
    items = []  # [text, style, line, first, last, line_length, first_line, column] where first/last tell whether it touches the line's start/end
    covered = {}
    for i, ((plain, runs), _) in enumerate(parsed):
        body = plain.rstrip()
        for s, e, style in runs:
            text = plain[s:e].strip()
            # a whole line with a background is a highlighted block (diff line, prompt box): lines mode has it
            if len(text) < MIN_SPAN or (style.bg and text == plain.strip()):
                continue
            end = s + len(plain[s:e].rstrip())
            start = s + len(plain[s:e]) - len(plain[s:e].lstrip())
            items.append([text, style, i, start == len(plain) - len(plain.lstrip()), end == len(body), len(body), i, start])
            covered.setdefault(i, []).append((start, end))
    merged = []
    for item in items:
        prev = merged[-1] if merged else None
        if (width and prev and prev[4] and item[3] and item[2] == prev[2] + 1 and item[1] == prev[1]
                and prev[5] + 1 + len(item[0].split()[0]) > width):
            prev[0] += " " + item[0]
            prev[2], prev[4], prev[5] = item[2], item[4], item[5]
        else:
            merged.append(item)
    return [(m[0], m[1], m[6], m[7]) for m in merged], covered


def choices(capture, mode, width=None):
    """[(text, display)] to pick from, in screen order: the text is what gets inserted, the display what fzf shows."""
    parsed = [(parse_line(raw), raw) for raw in capture.expandtabs(4).splitlines()]
    while parsed and not parsed[-1][0][0].strip():
        parsed.pop()
    if mode == "lines":
        icon = PATTERN_ICONS[icon_style()]["lines"]
        mark = f"\x1b[2m{icon}\x1b[0m " if icon else ""
        return [(plain.rstrip(), mark + OTHER_ESCAPES.sub("", raw).rstrip() + "\x1b[0m") for ((plain, _), raw) in parsed]
    icons = PATTERN_ICONS[icon_style()]
    mark = f"\x1b[2m{icons['spans']}\x1b[0m " if icons["spans"] else ""
    spans, covered = span_items(parsed, width)
    entries = [(line, col, text, f"{mark}{style.sgr()}{text}\x1b[0m") for text, style, line, col in spans]
    for line, ((plain, _), _) in enumerate(parsed):  # the patterns the program did not style itself
        for start, label, text in find_patterns(plain):
            if not any(start < e and s < start + len(text) for s, e in covered.get(line, [])):
                entries.append((line, start, text, (f"\x1b[2m{icons[label]}\x1b[0m " if icons[label] else "") + text))
    found = {}  # repeats stay once, at their latest position
    for _, _, text, display in sorted(entries, key=lambda e: e[:2]):
        found.pop(text, None)
        found[text] = display
    return list(found.items())

def compose(selection, mode):
    """The text to type for the picked items: lines joined by newlines (dedented). Anything else is joined by
    spaces, unless a pick itself has whitespace (a command, a phrase): then each pick gets its own line."""
    if mode == "lines":
        return textwrap.dedent("\n".join(selection)).strip("\n")
    if any(re.search(r"\s", item) for item in selection):
        return "\n".join(selection)
    return " ".join(selection)


BUFFER = "optmux-extract"


def tmux(*args, **kw):
    return subprocess.run(["tmux", *args], check=True, **kw)


def load_buffer(text, clipboard=False):
    """Put text in our own tmux buffer (and the clipboard via OSC 52 if asked). Through stdin, because as
    an argument tmux drops a trailing `;`, refuses more than ~16 KB, and keeps the old buffer when empty."""
    tmux("load-buffer", *(["-w"] if clipboard else []), "-b", BUFFER, "-", input=text, text=True)


def show_option(name):
    return subprocess.run(["tmux", "show-options", "-gqv", name], capture_output=True, text=True).stdout.strip()


def show_server_option(name):
    return subprocess.run(["tmux", "show-options", "-gsv", name], capture_output=True, text=True).stdout.strip()


def get_option(name, choices, default):
    value = show_option(name)
    return value if value in choices else default


def copy(text, method):
    if method == "osc52":
        # The escape goes to our own terminal: in a popup that is the client whose popup this is. (`load-buffer -w` leaves
        # the client to tmux, which picks the most recently active one: with several attached it may be another terminal.)
        # tmux passes it on, also over SSH, because set-clipboard is on.
        if sys.stdout.isatty() and show_server_option("set-clipboard") == "on":  # (tmux relays it from a pane or popup only then)
            load_buffer(text)
            sys.stdout.write(f"\x1b]52;c;{base64.b64encode(text.encode()).decode()}\x07")
            sys.stdout.flush()
        else:
            load_buffer(text, clipboard=True)
        return
    load_buffer(text)
    if method == "native":
        for cmd in (["pbcopy"], ["wl-copy"], ["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"]):
            if shutil.which(cmd[0]):
                subprocess.run(cmd, input=text, text=True, check=True)
                return
        raise RuntimeError("no system clipboard command found (pbcopy, wl-copy, xclip, xsel)")


STATE_OPTION = "@optmux-extract-at-"  # + the filter: where you left it, newest first (JSON: [{query, item}, ...])
MAX_ITEM = 300  # characters remembered of an item
MAX_HISTORY = 30  # queries remembered per filter


def load_history(name):
    """[(query, item)] last left in the filter `name`, newest first (an item may be None: not known)."""
    try:
        entries = json.loads(show_option(STATE_OPTION + name))
        return [(e["query"], e.get("item") if isinstance(e.get("item"), str) else None)
                for e in entries if isinstance(e, dict) and isinstance(e.get("query"), str)]
    except (ValueError, TypeError, KeyError):
        return []


def save_state(name, query, item):
    """Remember where the filter `name` was left: first in its history, the same query before it dropped."""
    try:
        entries = [(query[:MAX_QUERY], item[:MAX_ITEM] if item else None)]
        entries += [e for e in load_history(name) if e[0] != entries[0][0]]
        tmux("set-option", "-g", STATE_OPTION + name,
             json.dumps([{"query": q, "item": i} for q, i in entries[:MAX_HISTORY]], ensure_ascii=False))
    except (subprocess.CalledProcessError, OSError):
        pass  # (forgetting where you were is no reason to lose what you picked)


def fzf_order(numbered, query, shown):
    """The lines `fzf` would list for `query`, best match first (what `pos(N)` counts), or all of them."""
    lines = [f"{i}\t{t}\t{d}" for i, (t, d) in numbered]
    if not query:
        return lines
    out = subprocess.run(["fzf", "--ansi", "--filter", query, "--delimiter=\t", "--with-nth=3", "--tiebreak=index",
                          *(["--no-sort"] if shown == "lines" else [])],
                         input="\n".join(lines) + "\n", capture_output=True, text=True).stdout
    return out.splitlines()


def cursor_position(numbered, query, shown, item, recalled=False):
    """(query, position): where the cursor goes for `item`, 1-based from the best match. A recalled query that
    matches nothing now is dropped (an empty list is no way to come back), and an item no longer here gives None."""
    shown_lines = fzf_order(numbered, query, shown)
    if recalled and query and not shown_lines:
        query, shown_lines = "", fzf_order(numbered, "", shown)
    if item is not None:
        for n, line in enumerate(shown_lines, 1):
            if line.split("\t", 2)[1:2] and line.split("\t", 2)[1][:MAX_ITEM] == item:  # (an item is remembered cut to MAX_ITEM)
                return query, n
    return query, None


def cycle(values, current):
    return values[(values.index(current) + 1) % len(values)]


NARROW = 90  # columns; below this the hints shrink to fit
# keys that look the selection up in the project (optmux-find), and the source each starts in
FIND_KEYS = {"ctrl-f": "files", "ctrl-g": "grep", "ctrl-alt-f": "omni"}
MAX_QUERY = 200  # characters of selection handed to Find


def labels(filter_name, copier):
    """fzf's --header (two lines: editing keys, then the lookup keys) and --prompt: what is listed and which keys
    do what."""
    if shutil.get_terminal_size().columns < NARROW:
        return [f"--header=Up/Down;  Tab: multi;  Enter: insert;  C-y: copy ({copier}; C-t)\nC-u: clear;  M-p: older;  C-f: files;  C-g: grep;  C-M-f: all",
                f"--prompt={filter_name} (C-M-x) > "]
    return [f"--header=Up/Down to select;  Tab to multiselect;  Enter to insert;  C-y to copy ({copier}; C-t to switch)\n"
            "M-p/M-n: older/newer query;  C-u: clear;  in the project:  C-f files;  C-g grep;  C-M-f all",
            f"--prompt={filter_name} filtered (C-M-x to switch) > "]


PATH_POSITION = re.compile(r"^([^\s:]*[/.][^\s:]*):\d+(?::\d+)?$")  # path:line or path:line:col, as a program prints it
FZF_SYNTAX = re.compile(r"(^|\s)[\'^!]+|\$(?=\s|$)")  # fzf's 'exact ^prefix !negated suffix$: not part of the text


def find_query(chosen, typed):
    """The text to look up: the picks on one line (control bytes and extra whitespace gone, a `:line:col` after a
    path dropped, since a path has none), else what was typed in the filter (minus fzf's search syntax)."""
    words = [CONTROL_CHARS.sub(" ", pick).split() for pick in chosen]
    picks = [PATH_POSITION.sub(r"\1", " ".join(w)) for w in words if w]
    text = " ".join(picks).strip() or FZF_SYNTAX.sub(r"\1", CONTROL_CHARS.sub(" ", typed)).strip()
    return text[:MAX_QUERY]


def open_find(pane, source, query):
    """Hand the lookup to optmux Find: this popup closes and Find opens in a popup of its own (a popup's title cannot
    change, and this one says eXtract), started in `source` with `query`, working on `pane`'s project. The text
    goes in a file Find reads (and deletes), not in the command: tmux expands `#{...}` and `#(...)` in what
    `run-shell` is given. It is also kept in the tmux buffer, so a lookup that cannot start is not lost."""
    find = os.path.join(os.path.dirname(os.path.abspath(__file__)), "optmux-find")
    query_file = None
    try:
        load_buffer(query)
        path = tmux("display-message", "-p", "-t", pane, "#{pane_current_path}", capture_output=True, text=True).stdout.strip()
        with tempfile.NamedTemporaryFile("w", prefix="optmux-find-query-", delete=False) as f:  # (private: mode 600)
            f.write(query)
        query_file = f.name
        argv = [find, pane, f"--mode={source}", f"--query-file={f.name}"]
        if not os.access(find, os.X_OK):
            argv = [sys.executable, *argv]
        # display-popup expands formats in its -d too: `#` doubled once more
        directory = ["-d", path.replace("#", "##")] if path and os.path.isdir(path) else []
        popup = ["tmux", "display-popup", "-E", "-t", pane, *directory, "-w", "100%", "-h", "60%",
                 "-b", "rounded", "-T", " OPTMUX Find ", shlex.join(argv)]
        failed = shlex.join(["tmux", "display-message", "-d", "3000", "optmux-extract: could not open OPTMUX Find; the text is in the tmux buffer"])
        # in the background and a moment later: this popup has to be gone first, or the new one opens over it
        tmux("run-shell", "-b", f"sleep 0.2; {shlex.join(popup)} || {failed}".replace("#", "##"))
        return 0
    except (subprocess.CalledProcessError, OSError) as e:
        if query_file:
            try:
                os.unlink(query_file)
            except OSError:
                pass
        tmux("display-message", "-d", "3000", f"optmux-extract: could not start OPTMUX Find ({e}); the text is in the tmux buffer")
        return 1


def parse_fzf_output(stdout):
    """(query, key, texts) from `fzf --print-query --expect=...`; texts in screen order, not pick order."""
    query, key, *picked = stdout.split("\n")[:-1] or ["", "esc"]
    return query, key, [t for _, t in sorted((int(i), t) for i, t, _ in (c.split("\t", 2) for c in picked))]


def pick(pane):
    history = os.environ.get("OPTMUX_EXTRACT_HISTORY", "1000")
    capture = tmux(
        "capture-pane", "-p", "-e", "-J", "-S", f"-{history}", "-t", pane,
        capture_output=True, text=True,
    ).stdout
    width = int(tmux("display-message", "-p", "-t", pane, "#{pane_width}", capture_output=True, text=True).stdout)
    mode = get_option(FILTER_OPTION, FILTERS, FILTERS[0])
    copier = get_option(COPY_OPTION, COPIERS, COPIERS[0])
    query, remembered, back, recalled = "", None, -1, False  # (a fresh start; M-p steps `back` through the filter's earlier queries)
    while True:
        # fall through to the next filter when the remembered one has nothing here, without forgetting it
        shown = mode
        for _ in FILTERS:
            items = choices(capture, shown, width)
            if items:
                break
            shown = cycle(FILTERS, shown)
        else:
            tmux("display-message", "-d", "2000", "optmux-extract: nothing to pick on screen")
            return 1
        # newest first: fzf's default layout grows upward from the prompt, so the screen reads in its
        # natural order with the most recent choices under the cursor (and ahead among equal matches)
        numbered = list(reversed(list(enumerate(items))))
        # (after a filter switch the text just typed comes along; the cursor goes back only for M-p)
        query, pos = cursor_position(numbered, query, shown, remembered, recalled)
        recalled = False
        proc = subprocess.run(
            [
                "fzf", "--ansi", "--multi", "--tiebreak=index", *(["--no-sort"] if shown == "lines" else []),
                "--no-info", "--delimiter=\t", "--with-nth=3", "--print-query", f"--query={query}",
                *([f"--bind=load:pos({pos})+unbind(load)"] if pos else []),
                f"--expect=ctrl-alt-x,ctrl-t,ctrl-y,ctrl-c,esc,alt-p,alt-n,{','.join(FIND_KEYS)}",
                *labels(shown, copier),
            ],
            input="\n".join(f"{i}\t{t}\t{d}" for i, (t, d) in numbered), stdout=subprocess.PIPE, text=True,
        )
        if proc.returncode not in (0, 1, 130):
            input(f"[optmux-extract] fzf exited with status {proc.returncode}. Press Return/Enter to dismiss...")
        if proc.returncode not in (0, 1):
            return proc.returncode
        query, key, chosen = parse_fzf_output(proc.stdout)
        if key in ("alt-p", "alt-n"):  # older and newer queries of this filter, each with the item the cursor was on
            earlier = load_history(shown)
            was = back
            back = max(-1, min(back + (1 if key == "alt-p" else -1), len(earlier) - 1))
            if back != was:  # (at either end there is nowhere to go: what you typed stays)
                query, remembered = earlier[back] if back >= 0 else ("", None)
                recalled = True
            continue
        if query or (chosen and key not in ("ctrl-c", "esc", "ctrl-alt-x", "ctrl-t")):  # (leaving with nothing typed or picked saves nothing)
            save_state(shown, query, chosen[-1] if chosen else remembered)  # (the newest pick, or where it was)
        if key in FIND_KEYS:
            text = find_query(chosen, query)
            if not text:
                return 0
            return open_find(pane, FIND_KEYS[key], text)  # (this popup is done)
        elif key == "ctrl-alt-x":
            mode, remembered, back = cycle(FILTERS, shown), None, -1
            tmux("set-option", "-g", FILTER_OPTION, mode)
        elif key == "ctrl-t":
            copier = cycle(COPIERS, copier)
            tmux("set-option", "-g", COPY_OPTION, copier)
        elif key in ("ctrl-c", "esc") or not chosen:
            return 0
        else:
            text = compose(chosen, shown)
            if not text.strip():  # only blank lines picked: there is nothing to type or copy
                return 0
            if key == "ctrl-y":
                copy(text, copier)
                tmux("display-message", "-d", "1500", f"copied {len(text)} characters ({copier})")
            else:
                load_buffer(text)
                tmux("paste-buffer", "-p", "-r", "-d", "-b", BUFFER, "-t", pane)
            return 0


if __name__ == "__main__":
    if len(sys.argv) > 2:
        sys.exit(__doc__)
    # a popup's shell command is not format-expanded, but its TMUX env still points at the right session
    pane = sys.argv[1] if len(sys.argv) == 2 else tmux("display-message", "-p", "#{pane_id}", capture_output=True, text=True).stdout.strip()
    try:
        sys.exit(pick(pane))
    except Exception:  # the popup closes on exit, so keep the error on screen
        import traceback

        traceback.print_exc()
        input("[optmux-extract] failed. Press Return/Enter to dismiss...")
        sys.exit(1)
