#!/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-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 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 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"]
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.@%+=,~-]"
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 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)`)(?!\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 = m.group(1) if m.group(1) is not None else m.group(2)
        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 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 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") 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):
            # (a pattern inside a styled span is still listed, a path in a command; the span itself is not listed twice)
            end = start + len(text)
            inside = [(s, e) for s, e in covered.get(line, []) if start < e and s < end]
            if not inside if label == "quote" else (start, end) not in inside:  # (a styled quote is its span already)
                entries.append((line, min([s for s, _ in inside], default=start), 0, start, text, (f"\x1b[2m{icons[label]}\x1b[0m " if icons[label] else "") + text))
    for line, col, text in find_multiline_quotes([plain for ((plain, _), _) in parsed]):
        if not any(col < e and s < col + 1 for s, e in covered.get(line, [])):
            entries.append((line, col, 0, 0, text, (f"\x1b[2m{icons['quote']}\x1b[0m " if icons["quote"] else "") + text))
    stoplist = load_stoplist()
    found = {}  # repeats stay once, at their latest position
    for *_, text, display in sorted(entries, key=lambda e: e[:4]):
        if any(rx.fullmatch(text) for rx in stoplist):
            continue
        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:
        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]]
        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, paths="shown"):
    """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=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-p: older; M-r: paths {paths}",
                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);  C-e edit;  C-o open\n"
            f"C-u: clear;  find selection in:  C-f files,  C-g grep,  C-M-f all;  M-p/M-n: older/newer query;  M-r: paths {paths}",
            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 classify(pick):
    """What a pick is as a whole: url, 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", "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 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(path)
    if targets:
        return targets, None, None
    return [], None, f"no such file: {missing[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"]


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, 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 in ("path", "file"):
        full = resolve(split_position(pick)[0], cwd)
        if not os.path.exists(full):
            return 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


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])
    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(mode)
    query, remembered = earlier[0] if earlier else ("", None)
    back, recalled = (0 if earlier else -1), False  # (the query it opens on stays even if it matches nothing: C-u clears it)
    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-e,ctrl-o,alt-r,ctrl-c,esc,alt-p,alt-n,{','.join(FIND_KEYS)}",
                *labels(shown, copier, paths),
            ],
            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
        # 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(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 == "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__":
    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)
