#!/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 on the query you left, and `M-p` steps back through the filter's earlier queries (each with its
cursor), `M-n` forward again to a fresh start (`C-u` clears the query). `icons` (emoji, nerd or
text, as in optmux Find) says how a pattern's kind is drawn.

`C-r` opens the history of queries typed in the last weeks (all filters, most recent first, with when and how often)
as a popup over eXtract's prompt; Enter brings one back into the query.

`C-e` edits the selection in `$EDITOR` in a new pane (files at their `:line:col`, anything else through a temp file), `C-o`
opens it (files revealed in Finder, URLs in the browser, `#234` and commit hashes on GitHub), and `M-r` cycles how
paths are typed and copied: as shown, relative to the project, or absolute.

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 functools
import json
import math
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import textwrap
import time
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 is_grey(fg):
    """Whether a foreground is a mid grey: bright black, a 256-color grey (8, 59, 102, 145, or the ramp 232-250), or an
    RGB with nearly equal channels, neither near-white nor near-black. Programs draw their chrome and de-emphasized
    text in these; white (37, 7, 15, 255) is ordinary text, set explicitly."""
    if fg == (90,):
        return True
    if len(fg) == 3 and fg[:2] == (38, 5):
        return fg[2] in (8, 59, 102, 145) or 232 <= fg[2] <= 250
    if len(fg) == 5 and fg[:2] == (38, 2):
        r, g, b = fg[2:]
        return max(r, g, b) - min(r, g, b) <= 16 and 50 <= min(r, g, b) and max(r, g, b) <= 210
    return False


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"]
# Meta+digit picks the view, C-M-x steps through them (VIEW_ORDER), M-x back. M-1 spans and M-0 lines are the two FILTERS; the rest narrow the spans to a bucket of
# pattern kinds (the labels of PATTERN_SOURCES, plus "styled" for the program's own runs). To add a pattern, put its kind in
# a bucket (or leave it out: "others" takes whatever no bucket claims). Digits left free are for more buckets later.
KINDS = {  # bucket: (what the prompt calls it, the pattern kinds in it); None: everything not in another bucket
    "styled": ("colored, bold, stylized text", {"styled"}),
    "quotes": ("quoted text", {"quote"}),
    "others": ("anything else", None),
    "paths": ("paths, file names", {"path", "file"}),
    "refs": ("URLs, IPs, hashes, PRs, versions", {"url", "addr", "hash", "pr", "ver"}),  # what C-o opens
}
VIEW_KEYS = {"1": "spans", "2": "styled", "3": "quotes", "6": "others", "8": "paths", "9": "refs", "0": "lines"}
KIND_KEYS = {f"alt-{d}": view for d, view in VIEW_KEYS.items()}
VIEW_ORDER = ["spans", "styled", "quotes", "others", "paths", "refs", "lines"]  # what C-M-x cycles through
COPIERS = ["osc52", "native", "buffer"]
FILTER_OPTION = "@optmux-extract-filter"
COPY_OPTION = "@optmux-extract-copy"
PATH_STYLES = ["shown", "relative", "absolute"]
PATH_OPTION = "@optmux-extract-paths"

# 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.@%+=,~-]"
# (the `file` ones take what `+find: +known_files` adds: see compile_patterns)
PATTERN_SOURCES = [
    ("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}+)+/?|/(?![\w/.])(?<=[^/\s][^/\s]/))(?::\d+){{0,2}}"),  # dir/with/slash, .claude/
    ("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
    ("addr", r"(?<![\w.:/-])(?:(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)(?::\d{1,5})?|localhost:\d{1,5})(?![\w-]|\.\d)"),  # 192.168.1.100[:8080], localhost:3000
    ("ver", r"(?<![\w.])v?\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?(?!\.?\d)"),  # semver (not the tail of 192.168.1.100)
    ("file", r"(?<![\w/.~-])[\w-]+(?:\.[\w-]+)*\.@EXT@(?:\.\d+)*\b(?::\d+){0,2}"),  # name.ext[:line[:col]], lib.so.6
    ("file", r"(?<![\w/.~-])@NAMES@(?:\.[\w-]+)*\b(?::\d+){0,2}"),  # Makefile, Dockerfile.dev
    ("file", r"(?<![\w/.~)\]}$*-])\.[A-Za-z][\w-]*(?:\.[\w-]+)*\b(?::\d+){0,2}"),  # dotfiles: .env, .gitignore
    # quoted text: 'x' "x" `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. An apostrophe (don't) doesn't open a quote, and inside
    # one it only counts between letters ('don't stop'); \' and '' escapes are not understood.
    ("quote", r"(?<!\w)(?:`(?=\S)([^`\n]+?)(?<=\S)[`']|'(?=\S)((?:[^'\n]|(?<=\w)'(?=\w))+?)(?<=\S)'|\"(?=\S)([^\"\n]+?)(?<=\S)\""
     r"|“(?=\S)([^”\n]+?)(?<=\S)”|‘(?=\S)((?:[^’\n]|(?<=\w)’(?=\w))+?)(?<=\S)’)(?!\w)"),
]


def compile_patterns(extensions, names):
    """[(label, compiled)] for PATTERN_SOURCES. `extensions` are what a plain `[A-Za-z][A-Za-z0-9]{0,7}` misses (they start
    with a digit or run long), `names` the well-known files that have no extension (Makefile, Dockerfile.dev)."""
    alternatives = lambda words: "|".join(sorted(map(re.escape, dict.fromkeys(words)), key=len, reverse=True))
    ext = "(?:" + "".join(f"{a}|" for a in [alternatives(extensions)] if a) + "[A-Za-z][A-Za-z0-9]{0,7})"
    out = []
    for label, rx in PATTERN_SOURCES:
        if "@NAMES@" in rx and not names:
            continue
        out.append((label, re.compile(rx.replace("@EXT@", ext).replace("@NAMES@", "(?:" + alternatives(names) + ")"))))
    return out


@functools.lru_cache(maxsize=None)
def patterns_for(optmux_dir):
    """The compiled patterns with the `+find: +known_files` of $OPTMUX_DIR/find.json: groups of entries, `*.ext` an extension
    and anything else a file name."""
    if not optmux_dir:  # (not in an optmux session: no file to look for in whatever the current directory is)
        return compile_patterns((), ())
    try:
        groups = json.loads(open(os.path.join(optmux_dir, "find.json")).read()).get("known_files")
    except (OSError, ValueError, AttributeError):
        groups = None
    entries = [e for group in (groups.values() if isinstance(groups, dict) else []) for e in (group if isinstance(group, list) else [])
               if isinstance(e, str) and re.fullmatch(r"\*?\.?[\w.-]+", e)]
    return compile_patterns(tuple(e[2:] for e in entries if e.startswith("*.")), tuple(e for e in entries if not e.startswith("*.")))
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": "🔗", "addr": "🌐", "path": "📁", "file": "📄", "quote": "💬", "hash": "#️⃣", "pr": "🔀", "ver": "🏷️", "lines": "📃", "spans": "🎨"},
    "nerd": {"url": "\uf0c1", "addr": "\uf0ac", "path": "\uf07b", "file": "\uf016", "quote": "\uf10d", "hash": "\ue729", "pr": "\ue726", "ver": "\uf02b",
             "lines": "\uf0c9", "spans": "\uf1fc"},
    "none": {kind: "" for kind in ("url", "addr", "path", "file", "quote", "hash", "pr", "ver", "lines", "spans")},
    "text": {"url": "url ", "addr": "addr", "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(os.environ.get("OPTMUX_DIR", "")):
        for m in rx.finditer(plain):
            if label == "quote":
                i = next(i for i, g in enumerate(m.groups(), 1) if g is not None)
                text, (s, e) = m.group(i), m.span()
                # a quote around more than one thing (a command with a path in it) is listed too; one that is just a
                # path, a file... is that, listed once
                if text and (m.start(i), m.end(i)) not in taken:
                    found.append((s, label, text))
                continue
            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 load_stoplist():
    """Compiled `+find: +ignore_spans` patterns (every group; from $OPTMUX_DIR/find.json): spans never listed.
    A pattern that is not a valid regex is skipped."""
    try:
        groups = json.loads(open(os.path.join(os.environ["OPTMUX_DIR"], "find.json")).read()).get("ignore_spans")
    except (KeyError, OSError, ValueError, AttributeError):
        return []
    out = []
    for patterns in groups.values() if isinstance(groups, dict) else []:
        for pattern in patterns if isinstance(patterns, list) else []:
            try:
                out.append(re.compile(pattern, re.IGNORECASE))
            except (re.error, TypeError):
                pass
    return out


# a quote that runs over several lines (a program wraps its own text with newlines): only " and `, which seldom
# open without closing; no blank line inside, a closing quote has no space before it, so a stray one does not pair up
MULTILINE_QUOTE = re.compile(r"(?<!\w)(?:\"(?=\S)((?:[^\"\n]|\n(?!\s*\n)){1,800}?)(?<=\S)\"|`(?=\S)((?:[^`\n]|\n(?!\s*\n)){1,800}?)(?<=\S)`"
                             r"|“(?=\S)((?:[^”\n]|\n(?!\s*\n)){1,800}?)(?<=\S)”)(?!\w)")


def find_multiline_quotes(lines):
    """[(line, column, text)] for the quotes that span lines, their lines joined by single spaces."""
    text = "\n".join(lines)
    starts, pos = [], 0
    for line in lines:
        starts.append(pos)
        pos += len(line) + 1
    found = []
    for m in MULTILINE_QUOTE.finditer(text):
        inner = next(g for g in m.groups() if g is not None)
        if "\n" not in inner:
            continue  # (the one-line quotes are found line by line)
        first = max(i for i, st in enumerate(starts) if st <= m.start())
        found.append((first, m.start() - starts[first], re.sub(r"\s*\n\s*", " ", inner)))
    return 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
            # grey text with no emphasis is the program's chrome and asides (status lines, hints), not something to pick
            if is_grey(style.fg) and not style.bg and not style.attrs & {1, 4, 7}:
                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 in_bucket(bucket, kind):
    members = KINDS[bucket][1]
    if members is None:  # others: what no other bucket has
        return not any(m and kind in m for _, (_, m) in ((n, v) for n, v in KINDS.items()))
    return kind in members


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.
    `mode` is lines, spans, or a bucket of them (a key of KINDS)."""
    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 sort by line, column, then rank: a styled span follows the patterns inside it, so fzf shows the span first and a pattern is one skip away)
    entries = [(line, col, 1, 0, text, f"{mark}{style.sgr()}{text}\x1b[0m", "styled") for text, style, line, col in spans]
    for line, ((plain, _), _) in enumerate(parsed):  # the patterns, found in the plain text: what the program colored makes no difference
        for start, label, text in find_patterns(plain):
            end = start + len(text)
            inside = [s for s, e in covered.get(line, []) if start < e and s < end]  # (only to sort a pattern next to the span around it)
            entries.append((line, min(inside, default=start), 0, start, text, (f"\x1b[2m{icons[label]}\x1b[0m " if icons[label] else "") + text, label))
    for line, col, text in find_multiline_quotes([plain for ((plain, _), _) in parsed]):
        entries.append((line, col, 0, 0, text, (f"\x1b[2m{icons['quote']}\x1b[0m " if icons["quote"] else "") + text, "quote"))
    stoplist = load_stoplist()
    marks = "`'\"\u201c\u201d\u2018\u2019"
    styled_at = {(line, col): text for line, col, rank, _, text, _, kind in entries if kind == "styled"}
    sgr = {(line, col): style.sgr() for _, style, line, col in spans}

    def styled_here(line, start, text, kind):
        """The position of the styled span that is this pattern (a quote: with its marks), else None."""
        s = styled_at.get((line, start))
        if s is not None and (s == text or kind == "quote" and len(s) == len(text) + 2 and s[0] in marks and s[-1] in marks and s[1:-1] == text):
            return (line, start)

    # a pattern the program also styled whole (at the same place) is the more certain pick: it keeps its kind's icon and takes the
    # program's colors, and all spans list it as that, not as the bare span. A quote's styled span has its marks, so all spans keep
    # that span and drop the quote.
    confirmed = {(e[0], e[3]) for e in entries if e[6] not in ("styled", "quote") and styled_here(e[0], e[3], e[4], e[6])}
    found = {}  # the same text found twice stays once, at its latest position (the styled span, which sorts after the patterns)
    for line, col, rank, start, text, display, kind in sorted(entries, key=lambda e: e[:4]):
        if mode in KINDS and not in_bucket(mode, kind) or any(rx.fullmatch(text) for rx in stoplist):
            continue
        if mode == "spans" and (kind == "styled" and (line, col) in confirmed
                                or kind == "quote" and styled_at.get((line, start), text) != text and styled_here(line, start, text, kind)):
            continue
        if kind != "styled" and styled_here(line, start, text, kind):
            icon = f"\x1b[2m{icons[kind]}\x1b[0m " if icons[kind] else ""
            display = f"{icon}{sgr[(line, start)]}{text}\x1b[0m"
        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
RESUME_MINUTES = 5  # how long the last query stays the starting point (OPTMUX_EXTRACT_RESUME_MINUTES); after that M-p recalls it


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 left_at(name):
    """When the filter `name` was last left (epoch seconds), or 0 when unknown."""
    try:
        return float(json.loads(show_option(STATE_OPTION + name))[0].get("at", 0))
    except (ValueError, TypeError, KeyError, IndexError, AttributeError):
        return 0


def is_stale(name):
    try:
        minutes = float(os.environ.get("OPTMUX_EXTRACT_RESUME_MINUTES", RESUME_MINUTES))
    except ValueError:
        minutes = RESUME_MINUTES
    age = time.time() - left_at(name)
    return age < 0 or (minutes >= 0 and age > minutes * 60)  # (a clock that stepped back is no reason to keep it fresh)


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


QUERY_LOG_DAYS = 28  # how long C-r remembers a query (each one with when it was used)
QUERY_LOG_USES = 50  # times kept per query (enough to count a busy week)


def query_log_path():
    """Per project like optmux Find's state: $OPTMUX_DIR/extract/queries.json, else the user-wide XDG state dir."""
    base = os.environ.get("OPTMUX_DIR")
    d = os.path.join(base, "extract") if base else os.path.join(
        os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state"), "optmux")
    return os.path.join(d, "extract-queries.json" if not base else "queries.json")


def load_query_log(path=None):
    """{query: [epoch seconds it was used, newest first]}, or {} when there is none (or it is unreadable)."""
    try:
        with open(path or query_log_path()) as f:
            log = json.load(f)
        times = lambda ts: [float(t) for t in ts if isinstance(t, (int, float)) and math.isfinite(t)]
        return {q: ts for q, ts in ((q, times(ts)) for q, ts in log.items() if isinstance(q, str) and isinstance(ts, list))
                if ts}  # (an entry without a time is of no use)
    except FileNotFoundError:
        return {}
    except (OSError, ValueError, AttributeError):
        try:  # (unreadable: keep it aside, so the next write does not replace 28 days with one query)
            os.replace(path or query_log_path(), f"{path or query_log_path()}~")
        except OSError:
            pass
        return {}


def log_query(query, now=None, path=None):
    """Remember that `query` was used now (one line, as typed; blank ones are not worth recalling), and forget
    whatever was last used longer ago than QUERY_LOG_DAYS."""
    query = CONTROL_CHARS.sub(" ", query)[:MAX_QUERY]
    if not query.strip():
        return
    now = time.time() if now is None else now
    path = path or query_log_path()
    log = load_query_log(path)
    log[query] = [now, *log.get(query, [])][:QUERY_LOG_USES]
    cutoff = now - QUERY_LOG_DAYS * 86400
    log = {q: ts for q, ts in log.items() if ts and ts[0] >= cutoff}
    tmp = f"{path}.{os.getpid()}"
    try:
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(tmp, "w") as f:
            json.dump(log, f, ensure_ascii=False)
        os.replace(tmp, path)  # (whole or not at all: two popups may be leaving at once)
    except OSError:
        try:
            os.unlink(tmp)
        except OSError:
            pass  # (no history is no reason to lose what you picked)


def ago(seconds):
    """`now`, `5m`, `3h`, `2d`, `3w`: how long ago, roughly."""
    for unit, size in (("w", 604800), ("d", 86400), ("h", 3600), ("m", 60)):
        if seconds >= size:
            return f"{int(seconds // size)}{unit}"
    return "now"


def history_rows(log, now=None, extra=()):
    """C-r's list, most recently used first, one row per query: `last used, uses this week \\t query`.
    The first column is a fixed HISTORY_META_WIDTH wide, so the queries line up where the prompt ends. Queries in
    `extra` (the per-filter M-p histories, e.g. from before the log existed) follow, once, without a time."""
    now = time.time() if now is None else now
    rows = []
    for q, ts in sorted(log.items(), key=lambda kv: -kv[1][0]):
        week = sum(1 for t in ts if now - t < 604800)
        meta = f"{ago(max(0, now - ts[0])):<4}" + (f"×{week}" if week > 1 else "")
        rows.append(f"\x1b[2m{meta:<{HISTORY_META_WIDTH}}\x1b[0m\t{q}")
    rows += [" " * HISTORY_META_WIDTH + "\t" + q for q in dict.fromkeys(CONTROL_CHARS.sub(" ", q) for q in extra) if q.strip() and q not in log]
    return rows


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."""
    return cursor_position_and_count(numbered, query, shown, item, recalled)[:2]


def cursor_position_and_count(numbered, query, shown, item, recalled=False):
    """`cursor_position`, and how many lines match the query it returns (what the prompt counts)."""
    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, len(shown_lines)
    return query, None, len(shown_lines)


def history_name(mode):
    """The history a filter keeps its queries and time in: the kinds share the spans' (so M-p is the same wherever
    in the spans you are, and a kind is as fresh as the spans are)."""
    return "lines" if mode == "lines" else "spans"


def cycle(values, current, step=1):
    return values[(values.index(current) + step) % 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 view_bar(active, sep=",  ", cycle_hint="C-M-x/M-x to cycle:  "):
    """The line of M-digit keys, the active view in reverse bold, led by the key that cycles through them."""
    keys = sorted(VIEW_KEYS.items(), key=lambda kv: (kv[0] == "0", kv[0]))
    bar = sep.join(f"M-{d} " + (f"\x1b[1;7m{view}\x1b[0m" if view == active else view) for d, view in keys)
    return f"{cycle_hint}{bar}"


def prompt_for(view):
    """The prompt's fixed part: `spans[refs] (URLs, IPs, hashes, PRs, versions)`, or just `spans` or `lines`."""
    return f"spans[{view}] ({KINDS[view][0]})" if view in KINDS else view


# fzf keeps the prompt's counts current: `selected/matching`, the item under the cursor counting as selected when
# nothing is (Enter types it) and there is one. From fzf's own $FZF_SELECT_COUNT and $FZF_MATCH_COUNT.
PROMPT_COUNTS = ("result,multi:transform-prompt(s=$FZF_SELECT_COUNT; [ $s = 0 ] && [ $FZF_MATCH_COUNT -gt 0 ] && s=1; "
                 "printf '%s %s/%s > ' \"$OPTMUX_EXTRACT_PROMPT\" $s $FZF_MATCH_COUNT)")


def counted_prompt(view, matching):
    """fzf's --prompt as it will read once it has counted (`1/4`: the item under the cursor counts as selected), so
    it never flashes `0/0` first; PROMPT_COUNTS keeps it current from there."""
    return f"--prompt={prompt_for(view)} {min(matching, 1)}/{matching} > "


def labels(filter_name, copier, paths="shown"):
    """fzf's --header (the editing keys, the lookup keys, then the views, the active one highlighted) and --prompt:
    what is listed and which keys do what."""
    if shutil.get_terminal_size().columns < NARROW:
        return [f"--header=Tab: multi; Enter: type; C-y: copy ({copier}; C-t); C-e: edit; C-o: open\n"
                f"C-u: clear; C-f: files, C-g: grep, C-M-f: all; M-r: paths {paths}\n"
                f"C-r/M-p/M-n: history\n"
                + view_bar(filter_name, ", ", "C-M-x/M-x to cycle:\n"),
                f"--prompt={prompt_for(filter_name)} 0/0 > "]
    return [f"--header=Up/Down to select;  Tab to multiselect;  Enter to insert;  C-y to copy ({copier}; C-t to switch);  C-e edit;  C-o open\n"
            f"C-u: clear;  find selection in:  C-f files,  C-g grep,  C-M-f all;  C-r: query history (M-p/M-n: older/newer);  M-r: paths {paths}\n"
            + view_bar(filter_name),
            f"--prompt={prompt_for(filter_name)} 0/0 > "]


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 classify(pick):
    """What a pick is as a whole: url, addr, path, file, hash, pr, or other (anything that is not exactly one pattern)."""
    pick = pick.strip()
    found = find_patterns(pick)
    if len(found) == 1 and found[0][0] == 0 and found[0][2] == pick and found[0][1] in ("url", "addr", "path", "file", "hash", "pr"):
        return found[0][1]
    return "other"


POSITION = re.compile(r"^(.*?)(?::(\d+))?(?::(\d+))?$")


def split_position(pick):
    """(path, line, col) for `path[:line[:col]]`; line and col are None when absent."""
    path, line, col = POSITION.match(pick.strip()).groups()
    return path, line and int(line), col and int(col)


def resolve(path, cwd):
    return os.path.normpath(os.path.join(cwd, os.path.expanduser(path)))


def project_root(cwd):
    """The repository's top level, else `cwd` itself."""
    out = subprocess.run(["git", "-C", cwd, "rev-parse", "--show-toplevel"], capture_output=True, text=True).stdout.strip()
    return out if out and os.path.isdir(out) else cwd


def restyle(picks, style, cwd):
    """The picks with the paths among them (that exist) written relative to the project root or absolute; `shown` leaves them."""
    if style == "shown" or not any(classify(p) in ("path", "file") for p in picks):
        return picks
    root = os.path.realpath(project_root(cwd))  # (git's top level is symlink-free, so is the path compared to it)
    out = []
    for pick in picks:
        path, line, col = split_position(pick) if classify(pick) in ("path", "file") else (None, None, None)
        full = resolve(path, cwd) if path else None
        if not full or not os.path.exists(full):
            out.append(pick)
            continue
        text = full if style == "absolute" else os.path.relpath(os.path.realpath(full), root)
        out.append(text + "".join(f":{n}" for n in (line, col) if n is not None))
    return out


def editor_argv(editor, targets):
    """argv to edit [(path, line, col)] with the editor command `editor`. Helix and VS Code take `path:line:col`; nano
    and emacs `+LINE[,COL] path` for each file; vim (nvim, vi) one jump after startup, or with several files `-o` (a
    window each) and a `-c` that jumps in each window."""
    try:
        argv = shlex.split(editor) if editor and editor.strip() else []
    except ValueError:  # (unbalanced quotes)
        argv = []
    argv = argv or ["vi"]
    name = os.path.basename(argv[0])
    at = lambda l, c, sep: f"{l}{sep}{c}" if c else f"{l}"
    where = lambda p, l, c: p + "".join(f":{n}" for n in (l, c) if n is not None) if l else p
    if name in ("hx", "helix"):
        return argv + [where(*t) for t in targets]
    if name in ("code", "codium", "cursor"):
        return argv + [a for t in targets for a in (("-g", where(*t)) if t[1] else (t[0],))]
    if name in ("nano", "pico", "micro"):
        return argv + [a for p, l, c in targets for a in ((f"+{at(l, c, ',')}",) if l else ()) + (p,)]
    if name in ("emacs", "emacsclient"):
        return argv + [a for p, l, c in targets for a in ((f"+{at(l, c, ':')}",) if l else ()) + (p,)]
    if len(targets) == 1:  # (vim and anything unknown)
        p, l, c = targets[0]
        return argv + ([f"+call cursor({l},{c})" if c else f"+{l}"] if l else []) + [p]
    jumps = [a for n, (p, l, c) in enumerate(targets, 1) if l for a in ("-c", f"{n}wincmd w | call cursor({l},{c or 1})")]
    return argv + ["-o"] + [t[0] for t in targets] + (jumps + ["-c", "1wincmd w"] if jumps else [])


def notify(message):
    tmux("display-message", "-d", "2500", ("optmux-extract: " + message).replace("#", "##"))


def pane_directory(pane):
    path = tmux("display-message", "-p", "-t", pane, "#{pane_current_path}", capture_output=True, text=True).stdout.strip()
    return path if os.path.isdir(path) else os.getcwd()


def edit_plan(chosen, mode, cwd):
    """(targets, text, message): what to edit. Files that exist (with their position) when every pick is a path or
    URL, else (when none exists) the missing ones as new files whose directory exists; else the whole selection as
    text, for a temp file."""
    kinds = [classify(p) for p in chosen]
    if any(k not in ("path", "file", "url") for k in kinds):
        return [], compose(chosen, mode), None
    targets, missing = [], []
    for pick, kind in zip(chosen, kinds):
        if kind == "url":
            continue
        path, line, col = split_position(pick)
        full = resolve(path, cwd)
        if os.path.exists(full):
            targets.append((full, line, col))
        else:
            missing.append(((full, line, col), kind))
    if targets:
        return targets, None, None
    # nothing exists yet: edit the names as new files (a plan doc, say), when their directories are there to hold them
    # (a bare domain like docs.python.org is more likely a site than a file name)
    new = [t for t, k in missing if os.path.isdir(os.path.dirname(t[0])) and not (k == "file" and bare_domain(os.path.basename(t[0])))]
    if new:
        return new, None, None
    return [], None, f"no such file or directory: {missing[0][0][0]}" if missing else "URLs are opened with C-o, not edited"


def edit(pane, chosen, mode):
    cwd = pane_directory(pane)
    targets, text, message = edit_plan(chosen, mode, cwd)
    if message:
        notify(message)
        return 1
    temp = None
    if text is not None:
        if not text.strip():
            return 0
        with tempfile.NamedTemporaryFile("w", prefix="optmux-extract-", suffix=".txt", delete=False) as f:  # (private: mode 600)
            f.write(text + "\n")
        temp = f.name
        targets = [(temp, None, None)]
    command = shlex.join(editor_argv(os.environ.get("EDITOR"), targets)) + (f"; rm -f {shlex.quote(temp)}" if temp else "")
    # the editor is zoomed (-Z); when the window was zoomed on this pane already, quitting the editor hands the zoom back to it
    if tmux("display-message", "-p", "-t", pane, "#{window_zoomed_flag}", capture_output=True, text=True).stdout.strip() == "1":
        command += f"; tmux select-pane -Z -t {shlex.quote(pane)}"
    tmux("split-window", "-Z", *split_flags(pane), "-t", pane, "-c", cwd.replace("#", "##"), command)
    return 0


def split_flags(pane):
    """Open above, as optmux's other shortcuts do (the pane keeps its bottom edge), across the window's edge
    (-f) when the pane is too short to halve."""
    fits = os.path.join(os.path.dirname(os.path.abspath(__file__)), "optmux-split-fits")
    ok = subprocess.run([fits, pane], capture_output=True).returncode == 0
    return ["-v", "-b"] if ok else ["-f", "-v", "-b"]


# Top-level domains a bare name like docs.python.org is taken to end in, only when no such file exists. Deliberately
# short: anything that is also a common file extension (.py .sh .md .rs .pl .dev .app .me .co .cloud ...) stays a file.
DOMAIN_TLDS = {"com", "org", "net", "gov", "edu", "mil", "io", "us", "uk", "ca", "de", "fr", "jp", "kr", "cn", "au", "nl", "se", "ch", "eu", "biz", "xyz"}


def bare_domain(pick):
    """pick as an http:// URL when it is a bare domain name (docs.python.org, example.com), else None. A :port is not
    accepted, as it can't be told from :line."""
    m = re.fullmatch(r"(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+([A-Za-z]+)", pick)
    return f"http://{pick}" if m and m.group(1).lower() in DOMAIN_TLDS else None


def open_command(pick, cwd, system=None):
    """(argv, message) for opening a pick: a URL in the browser, a path revealed in the file manager, an IP address in the browser, a hash or PR/issue
    number on GitHub. argv is None when it cannot be opened, and the message says why."""
    system, pick = system or sys.platform, pick.strip()
    kind = classify(pick)
    opener = ["open"] if system == "darwin" else ["xdg-open"]
    if kind == "url":
        return opener + [pick], None
    if kind == "addr":
        return opener + [f"http://{pick}"], None
    if kind in ("path", "file"):
        full = resolve(split_position(pick)[0], cwd)
        if not os.path.exists(full):
            url = bare_domain(pick) if kind == "file" else None
            return (opener + [url], None) if url else (None, f"no such path: {pick}")
        return opener + ([] if os.path.isdir(full) or system != "darwin" else ["-R"]) + [full], None
    if kind in ("hash", "pr"):
        if not shutil.which("gh"):
            return None, f"{pick}: needs the gh command to open on GitHub"
        if subprocess.run(["git", "-C", cwd, "rev-parse", "--git-dir"], capture_output=True).returncode != 0:
            return None, f"{pick}: not in a git repository"
        return ["gh", "browse", pick.lstrip("#")], None
    return None, f"can't open: {pick[:40]}"


def run_open(argv, cwd):
    """Start the command; the error to show when it fails at once, else None (a long-lived opener is left running)."""
    try:
        proc = subprocess.Popen(argv, cwd=cwd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, start_new_session=True, text=True)
        try:
            code = proc.wait(5)
        except subprocess.TimeoutExpired:
            return None
        return None if code == 0 else f"{argv[0]} failed: {proc.stderr.read().strip()[:80]}"
    except OSError as e:
        return f"{argv[0]}: {e}"


def open_items(pane, chosen):
    cwd = pane_directory(pane)
    problems = []
    for pick in chosen:
        argv, message = open_command(pick, cwd)
        message = message or run_open(argv, cwd)
        if message:
            problems.append(message)
    if problems:
        notify("; ".join(problems))
    return 0


# ---- C-r: the query history, in a popup "on top of" eXtract's ------------------------------------------------
# A popup cannot open another popup (tmux just changes the one it is in), so C-r puts a lookalike of eXtract in its
# place, in floating panes (tmux 3.7+): its rounded, titled frame, and in it the same fzf with the same list,
# query and cursor, given no keys. eXtract's popup closes, and from `run-shell -b` (outside any popup) the history
# opens as a popup with its prompt on eXtract's prompt line. Then eXtract opens again as a popup on the query picked
# (showing a copy of the lookalike until its fzf draws), and the lookalike goes. Older tmux: no lookalike.

TITLE = " OPTMUX eXtract "  # as the shortcuts open it (optmux-defaults.yaml): display-popup -b rounded -T ...
HISTORY_ROWS = 12  # most rows the history popup takes
HISTORY_STYLE = "bg=colour237"  # the history popup's own look, so it reads as something on top, not eXtract
HISTORY_FZF_COLORS = "bg:237,bg+:239"
HISTORY_META_WIDTH = 9  # (+ the tab, shown as one column, + fzf's 2-column gutter = the width of HISTORY_PROMPT)
HISTORY_PROMPT = "history >".ljust(HISTORY_META_WIDTH + 3)


def has_floating_panes(version):
    """tmux 3.7+ (`new-pane`), going by the server's version (`3.8`, `3.7a`, `next-3.8`)."""
    m = re.search(r"(\d+)\.(\d+)", version)
    return bool(m) and (int(m[1]), int(m[2])) >= (3, 7)


def show_format(fmt, *target):
    return tmux("display-message", "-p", *target, fmt, capture_output=True, text=True).stdout.strip()


def popup_box(client_width, client_height, cols, rows):
    """(left, top, width, height) of the popup this runs in, border included, on the client: tmux centers a popup
    by its last row and column, (size - 1) / 2 + extent / 2 (measured: rows 25-103 of 132 for -h 60%)."""
    width, height = cols + 2, rows + 2
    return (max(0, (client_width - 1) // 2 + width // 2 - width), max(0, (client_height - 1) // 2 + height // 2 - height),
            width, height)


def status_rows(status, position, side):
    """Rows the status line takes on `side` ("top" or "bottom") of the client: `status` is on, off or a number
    of lines, `position` top or bottom."""
    lines = 0 if status == "off" else int(status) if status.isdigit() else 1
    return lines if position == side else 0


def frame(width, height, title=TITLE):
    """The popup's border, as text: ╭─ OPTMUX eXtract ──╮, │ │ down the sides, ╰──╯."""
    inner = width - 2
    top = ("─" + title + "─" * inner)[:inner]
    return "\x1b[?25l" + "\n".join(["╭" + top + "╮", *(["│" + " " * inner + "│"] * (height - 2)), "╰" + "─" * inner + "╯"])


def self_argv(*args):
    return [sys.executable, os.path.abspath(__file__), *args]


def shell(script, *args):
    """A popup or pane command: `sh -c script`, so the user's own shell (fish ...) never reads it."""
    return shlex.join(["sh", "-c", script, "sh", *args])


def lookalike_argv(config, query, pos, matching):
    """The fzf command line of eXtract as it is right now: the one it started with, the query typed since, the cursor
    where it is (`pos`, 1-based) and the prompt's count, so the lookalike never shows an older screen."""
    argv = [a for a in config["argv"] if not a.startswith(("--query=", "--bind=load:pos(", "--prompt="))]
    return [*argv, f"--query={query}", *([f"--bind=load:pos({pos})+unbind(load)"] if pos else []),
            counted_prompt(config["view"], matching)]


def prepare_history(d, query, pos, matching):
    """C-r, while eXtract is still on screen (fzf runs this and waits): the lookalike behind the popup (tmux 3.7+),
    drawn before the popup goes, so there is nothing to see in between. `d` holds what eXtract left for it."""
    with open(os.path.join(d, "config.json")) as f:
        config = json.load(f)
    with open(os.path.join(d, "query"), "w") as f:  # (what the history popup starts with: nothing, so every query is listed)
        f.write("")
    # (one question, not five)
    client, cw, ch, version, status, position = show_format(
        "#{client_tty}\t#{client_width}\t#{client_height}\t#{version}\t#{status}\t#{status-position}").split("\t")
    box = popup_box(int(cw), int(ch), config["cols"], config["rows"])
    state = dict(pane=config["pane"], client=client, box=box, shown=config["shown"], query=query, item=None, panes=[],
                 status_below=status_rows(status, position, "bottom"))
    if has_floating_panes(version):
        left, top, width, height = box
        y = top - status_rows(status, position, "top")
        with open(os.path.join(d, "frame"), "w") as f:
            f.write(frame(width, height))
        new = ["new-pane", "-d", "-B", "none", "-t", config["pane"], "-P", "-F", "#{pane_id}"]
        fzf = shlex.join(["env", f"OPTMUX_EXTRACT_PROMPT={prompt_for(config['view'])}",
                          *lookalike_argv(config, query, pos, matching)])
        state["panes"] = [  # (the frame, and inside it the same fzf with the same list: no key reaches it)
            tmux(*new, "-x", str(width), "-y", str(height), "-X", str(left), "-Y", str(y),
                 shell('cat "$1"; exec sleep 600', os.path.join(d, "frame")), capture_output=True, text=True).stdout.strip(),
            tmux(*new, "-x", str(width - 2), "-y", str(height - 2), "-X", str(left + 1), "-Y", str(y + 1),
                 f"{fzf} < {shlex.quote(os.path.join(d, 'items'))} > /dev/null; exec sleep 600",
                 capture_output=True, text=True).stdout.strip(),
        ]
        for _ in range(30):  # (a moment: it is only fzf)
            if prompt_for(config["view"]) in tmux("capture-pane", "-p", "-t", state["panes"][1],
                                                  capture_output=True, text=True).stdout:
                break
            time.sleep(0.01)
    with open(os.path.join(d, "state.json"), "w") as f:
        json.dump(state, f)


def prepare_history_from_fzf(d):
    """`--prepare-history D`, run by fzf on C-r with its query, cursor position and match count in the environment."""
    num = lambda name: int(os.environ.get(name) or 0)
    prepare_history(d, os.environ.get("FZF_QUERY", ""), num("FZF_POS"), num("FZF_MATCH_COUNT"))


def start_history(d, query, item, where):
    """C-r, after fzf has left: the history step, detached, to open as soon as this popup is gone. (The lookalike was
    made while fzf was still up; if that did not happen, it is made now, with `where()`: (cursor position, matches).)"""
    if not os.path.exists(os.path.join(d, "state.json")):
        prepare_history(d, query, *where())
    state = load_state(d)
    state["item"] = item
    with open(os.path.join(d, "state.json"), "w") as f:
        json.dump(state, f)
    open(os.path.join(d, "handoff"), "w").close()  # (the history step cleans up the directory, not this process)
    subprocess.Popen(self_argv("--history", d), start_new_session=True,
                     stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    return 0


def load_state(d):
    with open(os.path.join(d, "state.json")) as f:
        return json.load(f)


def show_history(d):
    """Detached from eXtract's popup: the history popup, then eXtract again (whatever goes wrong in between)."""
    state = load_state(d)
    try:
        return show_history_popup(d, state)
    except Exception:
        for pane in filter(None, state["panes"]):
            tmux("kill-pane", "-t", pane, capture_output=True)
        subprocess.run(["tmux", "display-popup", "-c", state["client"], "-E", "-w", str(state["box"][2]),
                        "-h", str(state["box"][3]), "-b", "rounded", "-T", TITLE,
                        shell('exec "$1" "$2" --resume "$3"', *self_argv()[:2], d)])


def show_history_popup(d, state):
    """The history popup itself, then the new eXtract popup."""
    left, top, width, height = state["box"]
    def at(name):
        return os.path.join(d, name)
    rows = history_rows(load_query_log(), extra=[q for name in ("spans", "lines") for q, _ in load_history(name)])
    with open(at("history"), "w") as f:
        f.write("\n".join(rows) + "\n" if rows else "")
    prompt_row = top + height - 2  # eXtract's prompt: the last row inside its border
    lines = max(8, min(HISTORY_ROWS, len(rows) + 2))  # (room for a few more, even while the list is short)
    client_height = int(show_format("#{client_height}", "-c", state["client"]))
    below = client_height - state["status_below"] - prompt_row  # (rows from the prompt down to the status line)
    layout, first = ("reverse", prompt_row) if below >= lines else ("default", prompt_row - lines + 1)
    with open(at("paint"), "w") as f:  # (the look and the prompt, put up before fzf is, so the popup never shows empty)
        f.write(f"\x1b[48;5;237m\x1b[2J\x1b[{1 if layout == 'reverse' else lines};1H{HISTORY_PROMPT}")
    script = (f'cat "$1/paint"; : > "$1/started"; fzf --ansi --layout="$2" --no-info --delimiter="\t" --nth=2 --tabstop=1 --tiebreak=index '
              f'--prompt="{HISTORY_PROMPT}" --color="{HISTORY_FZF_COLORS}" --print-query --no-scrollbar --query="$(cat "$1/query")" '
              f'< "$1/history" > "$1/out"; echo $? > "$1/status"')
    # display-popup's -y is the row under the popup (as for menus). While eXtract's popup is still closing, tmux
    # ignores this one (and we never started): so try again a moment later
    for _ in range(100):
        subprocess.run(["tmux", "display-popup", "-c", state["client"], "-B", "-s", HISTORY_STYLE, "-x", str(left + 1),
                        "-y", str(first + lines), "-w", str(width - 2), "-h", str(lines), "-E",
                        shell(script, d, layout)])
        if os.path.exists(at("started")):
            break
        time.sleep(0.03)
    try:
        with open(at("status")) as f:
            accepted = f.read().strip() in ("0", "1")  # (1: Enter on a typed query nothing in the history matches)
        with open(at("out")) as f:
            typed, *picked = f.read().split("\n")[:-1] or [""]
        chosen = (picked[0].split("\t", 1)[-1] if picked else typed) if accepted else ""
    except OSError:
        chosen = ""
    if not chosen:
        chosen = state["query"]  # (left with Esc, or never opened: eXtract as it was)
    with open(at("chosen"), "w") as f:
        f.write(chosen)
    if all(state["panes"]) and state["panes"]:  # the copy eXtract shows until its fzf draws, and the lookalike goes once it's up
        with open(at("snapshot"), "w") as f:
            f.write("\x1b[?25l" + tmux("capture-pane", "-e", "-p", "-t", state["panes"][1],
                                       capture_output=True, text=True).stdout.rstrip("\n"))
        kill = "; ".join(shlex.join(["tmux", "kill-pane", "-t", p]) for p in state["panes"])
        tmux("run-shell", "-b", f"sleep 0.15; {kill}".replace("#", "##"))
    subprocess.run(["tmux", "display-popup", "-c", state["client"], "-E", "-w", str(width), "-h", str(height),
                    "-b", "rounded", "-T", TITLE,
                    shell('cat "$1/snapshot" 2>/dev/null; exec "$2" "$3" --resume "$1"', d, *self_argv()[:2])])


def resume(d):
    """eXtract again, after the history: on the query picked (or as it was), in the same view, the cursor on the
    same item when the query is the same."""
    state = load_state(d)
    try:
        with open(os.path.join(d, "chosen")) as f:
            chosen = f.read()
    except OSError:
        chosen = state["query"]
    shutil.rmtree(d, ignore_errors=True)
    # (the query stays even if nothing matches it now, like the one eXtract opens on: C-u clears it)
    return pick(state["pane"], resume=dict(mode=state["shown"], query=chosen,
                                           item=state["item"] if chosen == state["query"] else None))


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, resume=None):
    d = tempfile.mkdtemp(prefix="optmux-extract-")  # (what C-r needs from this run; gone with it, unless handed over)
    try:
        return run_pick(pane, resume, d)
    finally:
        if not os.path.exists(os.path.join(d, "handoff")):
            shutil.rmtree(d, ignore_errors=True)


def run_pick(pane, resume, d):
    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 + list(KINDS), FILTERS[0])
    if mode in KINDS and is_stale("spans"):  # (like the query, a kind view is a few minutes' business: then all spans)
        mode = "spans"
        tmux("set-option", "-g", FILTER_OPTION, mode)  # (for good: leaving refreshes the time, and the old kind must not come back)
    copier = get_option(COPY_OPTION, COPIERS, COPIERS[0])
    paths = get_option(PATH_OPTION, PATH_STYLES, PATH_STYLES[0])
    # opens on the filter's last query and item (M-p steps `back` through the earlier ones, M-n forward to a fresh start)
    earlier = load_history(history_name(mode))
    fresh = not earlier or is_stale(history_name(mode))  # (a query left minutes ago is likely still wanted; one from hours ago is in the way)
    query, remembered = ("", None) if fresh else earlier[0]
    back, recalled = (-1 if fresh else 0), False
    if resume:  # (back from C-r's history: the view it was in, the query picked, and the item when it is the same query)
        # (the query stays even if nothing matches it now, like the one eXtract opens on: C-u clears it)
        mode, query, remembered, back = resume["mode"], resume["query"], resume["item"], -1
    while True:
        # fall through to the next filter when the remembered one has nothing here, without forgetting it
        # (a kind with nothing here shows all spans, and the prompt says so)
        shown = mode
        for _ in FILTERS:
            items = choices(capture, shown, width)
            if items or shown in KINDS:  # (a bucket with nothing stays empty, `0/0` in the prompt, instead of showing something else)
                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, matching = cursor_position_and_count(numbered, query, shown, remembered, recalled)
        recalled = False
        header = labels(shown, copier, paths)[0]
        marker = os.path.join(d, "ctrl-r")
        fzf_argv = [
                "fzf", "--ansi", "--multi", "--tiebreak=index", *(["--no-sort"] if shown == "lines" else []),
                "--no-info", f"--bind={PROMPT_COUNTS}", "--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,alt-x,ctrl-t,ctrl-y,ctrl-e,ctrl-o,alt-r,ctrl-c,esc,alt-p,alt-n,{','.join(FIND_KEYS)},{','.join(KIND_KEYS)}",
                header, counted_prompt(shown, matching),
                f"--bind=ctrl-r:execute-silent({shlex.join(self_argv('--prepare-history', d))}; touch {shlex.quote(marker)})+accept",
            ]
        items_text = "\n".join(f"{i}\t{t}\t{d}" for i, (t, d) in numbered)
        if os.path.exists(marker):
            os.unlink(marker)
        with open(os.path.join(d, "items"), "w") as f:  # (what C-r's lookalike lists, written now: fzf runs it on the key)
            f.write(items_text)
        with open(os.path.join(d, "config.json"), "w") as f:
            json.dump(dict(pane=pane, shown=shown, view=shown, argv=fzf_argv, cols=shutil.get_terminal_size().columns,
                           rows=shutil.get_terminal_size().lines), f)
        env = {**os.environ, "OPTMUX_EXTRACT_PROMPT": prompt_for(shown)}
        proc = subprocess.run(fzf_argv, input=items_text, stdout=subprocess.PIPE, text=True, env=env)
        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 os.path.exists(marker):  # (C-r is a binding, not a key fzf reports: it left a mark)
            key = "ctrl-r"
        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(history_name(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
        # however you leave (Esc too), the filter is left as it is, an emptied query included: `C-u`, then Esc, stays cleared
        if key not in ("ctrl-t", "alt-r"):  # (switching the copy method stays in the same session, and would shift the M-p index)
            save_state(history_name(shown), query, chosen[-1] if chosen else remembered)  # (the newest pick, or where it was)
        if key not in ("ctrl-t", "alt-r"):
            log_query(query)  # (what C-r recalls: anything you left a query as, picked from or not)
        if key == "ctrl-r":  # the history: this popup closes, and it opens (see start_history)
            item = chosen[-1] if chosen else remembered
            return start_history(d, query, item, lambda: cursor_position_and_count(numbered, query, shown, item)[1:])
        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 in ("ctrl-alt-x", "alt-x") or key in KIND_KEYS:
            # C-M-x steps through the views, from the one on screen (not `mode`, which may have fallen through)
            mode = KIND_KEYS[key] if key in KIND_KEYS else cycle(VIEW_ORDER, shown, -1 if key == "alt-x" else 1)
            remembered, back = 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 == "alt-r":
            paths = cycle(PATH_STYLES, paths)
            tmux("set-option", "-g", PATH_OPTION, paths)
        elif key in ("ctrl-c", "esc") or not chosen:
            return 0
        elif key == "ctrl-e":
            return edit(pane, chosen, shown)
        elif key == "ctrl-o":
            return open_items(pane, chosen)
        else:
            if paths != "shown":
                chosen = restyle(chosen, paths, pane_directory(pane))
            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__":
    # the steps of C-r's history run as this script too (see start_history); each takes the directory it keeps its state in
    steps = {"--history": show_history, "--resume": resume, "--prepare-history": prepare_history_from_fzf}
    if len(sys.argv) > 2 and sys.argv[1] in steps:
        sys.exit(steps[sys.argv[1]](*sys.argv[2:]) or 0)
    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)
