Files
openidea/src/features/vcs/conflicts.ts
T
l0ng-ai 82b6980a59 feat: Second pass aligning interactions with IntelliJ IDEA (#23)
* feat: Second pass aligning interactions with IntelliJ IDEA

Result tool windows
- Next/Previous Occurrence (⌥⌘↓/↑) across Find, Usages, Problems, TODO,
  Inspection and Hierarchy, with an "N of M" status hint
- Find: reuse the unpinned tab, Pin Tab, source preview, group by file or
  directory, exclude moves to the next result, Rerun
- Usages: tabs with pinning, exclude and preview
- Problems, TODO, Inspection: no autoscroll by default, severity-first sorting,
  context menu with quick fixes and copy description
- Trees: F4/⌘↓ jump to source; speed search Home/End and arrow handling

Find in Files, bookmarks, navigation
- Replace mode: Enter replaces the selection, ⇧⌥Enter replaces all, multi-select
- Pin Window toggle, highlighted read-only preview, search/replace history (⌥↓),
  Alt mnemonics, search context filter (comments / string literals)
- Mnemonic bookmarks (⌥F3, ⌃⇧digit, ⌃digit), ⌘F3 bookmarks popup, descriptions,
  ⌘-click gutter toggles a bookmark
- Select In popup (⌥F1); Recent Locations double-click and Delete;
  Search Everywhere remembers the query per tab

Code insight and refactoring
- Extract/Introduce continue with in-place rename and name suggestions;
  expression and occurrence choosers with live highlighting
- Safe Delete confirms first; numbered Refactor This
- Quick Documentation history, in-popup links and a Documentation tool window;
  Quick Definition switches between targets and shows the whole declaration
- Goto chooser lists symbol names and can pin to the Find window
- Parameter Info Tab/⇧Tab, intention preview, Reformat dialog and summary,
  inlay hint ⌘-click and context menu
- Live templates: Enter moves to the next field, two-step Esc, ⌘J as a lookup,
  language surrounders with mnemonics
- File Structure popup as a filterable tree; Show Usages filter and preview;
  call hierarchy jumps to call sites

Editor
- Paste re-indents each line by default; Move Statement moves whole statements
  in and out of blocks and re-indents
- Type over closing quotes of existing strings; ⌘D/⌘⌫ cover folded regions;
  ⌥⌫ deletes the preceding word
- ⌃G / ⌃⌘G whole-word rules and wrap hint; double-modifier caret cloning
- Visual-column block selection, nested Collapse All, recursive folding,
  fold selection toggle, Go to Matching Brace, gutter drag selects lines,
  sticky line and error stripe clicks, Insert toggles overwrite mode

Run, VCS, workbench
- Gutter icons show the last test result; Modify Run Configuration; test tree
  hides passed tests, context menu and assertion diff
- Stack frames resolve by fully qualified class name; context run chooser
- Inline Smart Step Into
- Git Log multi-select filters, "me" and date range; favourite branches,
  Fetch and tags in the branch popup; stash Keep index and Unstash options
- Terminal tab titles follow the shell; Distraction Free persists; gear menu;
  sticky balloons move to the notifications tool window after a while

* fix(vcs): Label restored local changes as yours after Smart Checkout; name the branch checked out

Conflicts from restoring stashed changes show the user's uncommitted
changes on the left like other operations, and the checkout notification
names the new branch instead of the previous one.

* fix: Close the merge editor on Apply; confirm before terminating a running Run tab

Like IDEA, applying a merge result closes its tab, and closing a Run tab
whose process still runs asks before terminating it (with a Settings
toggle and "Do not ask again").

* fix(terminal): Don't start a new session in the background after closing the last tab

The hidden Terminal window stays mounted, so it reopened a session as soon
as the last tab closed. It now opens the Local tab only once the window is
shown again, as IDEA does.

* fix(vcs): Start the merge result from a three-way merge; close the editor on Apply

The result pane now begins with non-conflicting changes merged and each
conflict showing the base text, resolved from the side panes, instead of
raw conflict markers. Apply now reports success, so the tab closes.

fix(search): Match File Structure filter on word starts

* fix: Limit Smart Step Into to the paused line; drop usages hints on callbacks; show full intention titles

Adapters that list every remaining call in the function (debugpy) made Smart
Step Into fall back to a chooser that offered calls from later lines. Targets
are now narrowed to the calls on the paused line, so they are picked in place.

Anonymous functions and callbacks no longer get a 'no usages' hint, and
intention titles are no longer cut short when there is room for them.

* fix: Undo / Redo from the Edit menu and Find Action use the editor's history

They ran the webview's native undo, which misses programmatic edits such as
templates, completion and refactorings, so nothing happened in the editor.
2026-10-25 09:44:46 +08:00

193 lines
6.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** Git conflict marker parsing and resolution (pure). */
import type { MergeSides } from "@/bindings";
export interface ConflictBlock {
/** Offset of the `<<<<<<<` line start. */
from: number;
/** Offset just past the `>>>>>>>` line (including its terminator). */
to: number;
ours: string;
/** diff3 base section, when present. */
base: string | null;
theirs: string;
oursLabel: string;
theirsLabel: string;
/** Offsets of the separator lines (for decorations). */
oursFrom: number;
oursTo: number;
theirsFrom: number;
theirsTo: number;
}
const START = "<<<<<<<";
const BASE = "|||||||";
const SEP = "=======";
const END = ">>>>>>>";
const isMarker = (line: string, marker: string) =>
line.startsWith(marker) && (line.length === 7 || line[7] === " " || line[7] === "\r" || line[7] === "\n");
/** Finds well-formed conflict blocks in `text`. */
export function parseConflicts(text: string): ConflictBlock[] {
const out: ConflictBlock[] = [];
const lines: Array<{ from: number; text: string; end: number }> = [];
let pos = 0;
while (pos < text.length) {
const nl = text.indexOf("\n", pos);
const end = nl < 0 ? text.length : nl + 1;
lines.push({ from: pos, text: text.slice(pos, end), end });
pos = end;
}
for (let i = 0; i < lines.length; i++) {
const start = lines[i]!;
if (!isMarker(start.text, START)) continue;
let baseAt = -1;
let sepAt = -1;
let endAt = -1;
for (let j = i + 1; j < lines.length; j++) {
const t = lines[j]!.text;
if (isMarker(t, START)) break;
if (sepAt < 0 && baseAt < 0 && isMarker(t, BASE)) baseAt = j;
else if (sepAt < 0 && isMarker(t, SEP)) sepAt = j;
else if (sepAt >= 0 && isMarker(t, END)) {
endAt = j;
break;
}
}
if (sepAt < 0 || endAt < 0) continue;
const slice = (a: number, b: number) => (a >= b ? "" : text.slice(lines[a]!.from, lines[b - 1]!.end));
const oursEnd = baseAt >= 0 ? baseAt : sepAt;
const label = (l: string, m: string) => l.slice(m.length).trim();
out.push({
from: start.from,
to: lines[endAt]!.end,
ours: slice(i + 1, oursEnd),
base: baseAt >= 0 ? slice(baseAt + 1, sepAt) : null,
theirs: slice(sepAt + 1, endAt),
oursLabel: label(start.text, START),
theirsLabel: label(lines[endAt]!.text, END),
oursFrom: lines[i + 1]?.from ?? start.end,
oursTo: lines[oursEnd]!.from,
theirsFrom: lines[sepAt]!.end,
theirsTo: lines[endAt]!.from,
});
i = endAt;
}
return out;
}
/** A choice in user terms: "ours" is the user's work ("Accept Yours"). */
export type Resolution = "ours" | "theirs" | "both" | "base";
/**
* Text replacing `block`. With `reversed` (a rebase, where git writes the upstream as
* the `<<<<<<<` section and the user's commit as `>>>>>>>`) the sides swap, as IDEA does.
*/
export function resolutionText(
block: Pick<ConflictBlock, "ours" | "base" | "theirs">,
how: Resolution,
reversed = false,
): string {
const yours = reversed ? block.theirs : block.ours;
const theirs = reversed ? block.ours : block.theirs;
switch (how) {
case "ours":
return yours;
case "theirs":
return theirs;
case "base":
return block.base ?? "";
case "both":
return yours && !yours.endsWith("\n") ? `${yours}\n${theirs}` : yours + theirs;
}
}
/** Resolves every block the same way. */
export function resolveAll(text: string, how: Resolution, reversed = false): string {
const blocks = parseConflicts(text);
let out = "";
let pos = 0;
for (const b of blocks) {
out += text.slice(pos, b.from) + resolutionText(b, how, reversed);
pos = b.to;
}
return out + text.slice(pos);
}
export function blockAt(blocks: readonly ConflictBlock[], offset: number): ConflictBlock | undefined {
return blocks.find((b) => b.from <= offset && offset < Math.max(b.to, b.from + 1));
}
/**
* Merge editor pane titles for the operation in progress (as IDEA
* labels them). English source text, to be passed through `txTemplate`.
*/
export function mergeTitles(sides: MergeSides | null | undefined): { yours: string; theirs: string } {
const branch = sides?.branch ?? null;
const commit = sides?.commit ?? null;
const other = sides?.otherBranch ?? null;
switch (sides?.operation) {
case "rebase":
return {
yours: commit && branch ? `Rebasing ${commit} from ${branch}` : "Your changes",
theirs: other ? `Already rebased commits and commits from ${other}` : "Already rebased commits",
};
case "merge":
return {
yours: branch ? `Changes from ${branch}` : "Your version",
theirs: other ? `Changes from ${other}` : commit ? `Changes from ${commit}` : "Changes from diverging branches",
};
case "unstash":
return {
yours: "Your uncommitted changes",
theirs: branch ? `Changes from ${branch}` : "Changes from remote",
};
case "cherry-pick":
return {
yours: "Local Changes",
theirs: commit ? `Changes from cherry-pick ${commit}` : "Changes from cherry-pick",
};
default:
return {
yours: branch ? `Your version, branch ${branch}` : "Your version",
theirs: commit ? `Changes from ${commit}` : "Theirs (incoming)",
};
}
}
/** An unresolved conflict in the merge editor's result: `from`–`to` holds the base text. */
export interface ResultConflict {
from: number;
to: number;
/** The user's side ("Accept Yours"). */
ours: string;
base: string | null;
theirs: string;
}
/**
* The merge editor's starting result, as IDEA shows it: the merged text with every
* conflict block replaced by its base section, so no markers appear. `reversed` swaps
* the sides of marker sections written in git's order (a rebase).
*/
export function initialResult(merged: string, reversed = false): { text: string; conflicts: ResultConflict[] } {
const conflicts: ResultConflict[] = [];
let text = "";
let pos = 0;
for (const b of parseConflicts(merged)) {
text += merged.slice(pos, b.from);
const base = b.base ?? "";
const from = text.length;
text += base;
conflicts.push({
from,
to: text.length,
ours: reversed ? b.theirs : b.ours,
base: b.base,
theirs: reversed ? b.ours : b.theirs,
});
pos = b.to;
}
return { text: text + merged.slice(pos), conflicts };
}