add search-and-replace across files

Builds on the find-in-files engine. A replace engine applies the
query's replacement to each matching file — literal or regex with
capture-group expansion ($1, $&, $$) — and reports per-file, per-line
before/after edits computed with the same logic the apply uses, so
preview and apply never disagree.

The search.replace command previews (no disk writes) or applies
(writing each changed file through the workspace path-safety guard).
The panel gains a Replace field: each match row previews its rewritten
line, and Replace all is gated on a clean git working tree (git is the
undo) plus a confirmation before it writes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-31 21:41:09 +02:00
co-authored by Claude Opus 4.8
parent d26a1f895c
commit 4aed6c12a5
11 changed files with 821 additions and 8 deletions
@@ -27,6 +27,7 @@ class FindInFilesController extends ChangeNotifier {
bool ignoreCase = false;
String includeGlobs = '';
String excludeGlobs = '';
String replacement = '';
// -- Result state ---------------------------------------------------------
String? _activeSearchId;
@@ -67,6 +68,42 @@ class FindInFilesController extends ChangeNotifier {
set include(String v) => includeGlobs = v;
set exclude(String v) => excludeGlobs = v;
void setReplacement(String v) {
if (replacement == v) return;
replacement = v;
notifyListeners();
}
/// True when the git working tree has no changes — the safety gate for
/// applying a destructive multi-file replace (the user's chosen model:
/// git is the lossless undo layer).
Future<bool> isWorkingTreeClean() async {
final r = await ipc.request('git.status');
return r.ok && r.data['clean'] == true;
}
/// Apply the current replacement across all matches, then refresh the
/// results. Returns the number of files changed and matches replaced.
/// Callers must gate on [isWorkingTreeClean] + user confirmation first.
Future<({int files, int count})> applyReplace() async {
final r = await ipc.request('search.replace', args: {
'pattern': pattern,
'regex': regex,
'ignoreCase': ignoreCase,
'include': _split(includeGlobs),
'exclude': _split(excludeGlobs),
'replacement': replacement,
'apply': true,
});
final files = (r.data['filesChanged'] as num?)?.toInt() ?? 0;
final count = (r.data['totalCount'] as num?)?.toInt() ?? 0;
await run(pattern); // refresh the match list against the new content
return (files: files, count: count);
}
/// The query the panel is currently running (for preview rendering).
SearchQuery get query => SearchQuery(pattern: pattern, regex: regex, ignoreCase: ignoreCase);
/// Start a search with the current query/options. Cancels any
/// in-flight search first and clears prior results.
Future<void> run(String query) async {
+221 -8
View File
@@ -6,6 +6,7 @@ library;
import 'package:clide/builtin/search/src/find_in_files_controller.dart';
import 'package:clide/kernel/kernel.dart';
import 'package:clide/src/search/match.dart';
import 'package:clide/src/search/replace_engine.dart';
import 'package:clide/widgets/widgets.dart';
import 'package:flutter/widgets.dart';
@@ -33,6 +34,26 @@ class _SearchPanelViewState extends State<SearchPanelView> {
super.dispose();
}
Future<void> _replaceAll() async {
final c = _controller!;
if (c.replacement.isEmpty || c.matchCount == 0) return;
final dialog = ClideKernel.of(context).dialog;
if (!await c.isWorkingTreeClean()) {
await dialog.show<Object>((ctx, dismiss) => _MessageDialog(
title: 'Working tree not clean',
body: 'Commit or stash your changes before replacing — git is the only undo.',
dismiss: dismiss,
));
return;
}
final confirmed = await dialog.show<bool>((ctx, dismiss) => _ConfirmDialog(
body: 'Replace ${c.matchCount} match(es) across ${c.fileCount} file(s)? This cannot be undone in clide.',
dismiss: dismiss,
));
if (confirmed != true) return;
await c.applyReplace();
}
@override
Widget build(BuildContext context) {
final tokens = ClideTheme.of(context).surface;
@@ -79,6 +100,18 @@ class _SearchPanelViewState extends State<SearchPanelView> {
],
),
const SizedBox(height: 6),
Row(
children: [
Expanded(child: ClideFilterBox(hint: 'Replace', debounce: Duration.zero, onChanged: c.setReplacement)),
const SizedBox(width: 6),
_ReplaceAllButton(
enabled: c.replacement.isNotEmpty && c.matchCount > 0,
tokens: tokens,
onTap: _replaceAll,
),
],
),
const SizedBox(height: 6),
ClideFilterBox(hint: 'files to include (e.g. *.dart)', debounce: Duration.zero, onChanged: (v) => c.include = v),
const SizedBox(height: 4),
ClideFilterBox(hint: 'files to exclude', debounce: Duration.zero, onChanged: (v) => c.exclude = v),
@@ -94,7 +127,15 @@ class _SearchPanelViewState extends State<SearchPanelView> {
child: ListView(
padding: EdgeInsets.zero,
children: [
for (final entry in groups.entries) _FileGroup(path: entry.key, matches: entry.value, tokens: tokens, onTap: c.openMatch),
for (final entry in groups.entries)
_FileGroup(
path: entry.key,
matches: entry.value,
tokens: tokens,
onTap: c.openMatch,
query: c.query,
replacement: c.replacement,
),
],
),
),
@@ -169,12 +210,21 @@ class _StatusText extends StatelessWidget {
}
class _FileGroup extends StatelessWidget {
const _FileGroup({required this.path, required this.matches, required this.tokens, required this.onTap});
const _FileGroup({
required this.path,
required this.matches,
required this.tokens,
required this.onTap,
required this.query,
required this.replacement,
});
final String path;
final List<SearchMatch> matches;
final SurfaceTokens tokens;
final void Function(SearchMatch) onTap;
final SearchQuery query;
final String replacement;
@override
Widget build(BuildContext context) {
@@ -193,18 +243,26 @@ class _FileGroup extends StatelessWidget {
],
),
),
for (final m in matches) _MatchRow(match: m, tokens: tokens, onTap: () => onTap(m)),
for (final m in matches) _MatchRow(match: m, tokens: tokens, onTap: () => onTap(m), query: query, replacement: replacement),
],
);
}
}
class _MatchRow extends StatelessWidget {
const _MatchRow({required this.match, required this.tokens, required this.onTap});
const _MatchRow({
required this.match,
required this.tokens,
required this.onTap,
required this.query,
required this.replacement,
});
final SearchMatch match;
final SurfaceTokens tokens;
final VoidCallback onTap;
final SearchQuery query;
final String replacement;
@override
Widget build(BuildContext context) {
@@ -224,7 +282,7 @@ class _MatchRow extends StatelessWidget {
width: 36,
child: ClideText('${match.line}', fontSize: clideFontCaption, fontFamily: clideMonoFamily, color: tokens.globalTextMuted),
),
Expanded(child: _highlighted()),
Expanded(child: replacement.isEmpty ? _highlighted() : _preview()),
],
),
),
@@ -232,19 +290,174 @@ class _MatchRow extends StatelessWidget {
);
}
TextStyle get _base => TextStyle(fontFamily: clideMonoFamily, fontSize: clideFontCaption, color: tokens.sidebarForeground);
Widget _highlighted() {
final line = match.preview;
final start = match.matchStart.clamp(0, line.length);
final end = match.matchEnd.clamp(start, line.length);
final base = TextStyle(fontFamily: clideMonoFamily, fontSize: clideFontCaption, color: tokens.sidebarForeground);
return RichText(
maxLines: 1,
overflow: TextOverflow.ellipsis,
text: TextSpan(style: base, children: [
text: TextSpan(style: _base, children: [
TextSpan(text: line.substring(0, start)),
TextSpan(text: line.substring(start, end), style: base.copyWith(color: tokens.globalFocus, fontWeight: FontWeight.bold)),
TextSpan(text: line.substring(start, end), style: _base.copyWith(color: tokens.globalFocus, fontWeight: FontWeight.bold)),
TextSpan(text: line.substring(end)),
]),
);
}
/// Replace-preview: the original line struck through, then the
/// rewritten line (computed with the same engine the apply uses).
Widget _preview() {
final after = applyToText(match.preview, query, replacement).text;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
RichText(
maxLines: 1,
overflow: TextOverflow.ellipsis,
text: TextSpan(text: match.preview, style: _base.copyWith(decoration: TextDecoration.lineThrough, color: tokens.globalTextMuted)),
),
RichText(
maxLines: 1,
overflow: TextOverflow.ellipsis,
text: TextSpan(text: after, style: _base.copyWith(color: tokens.globalFocus)),
),
],
);
}
}
class _ReplaceAllButton extends StatelessWidget {
const _ReplaceAllButton({required this.enabled, required this.tokens, required this.onTap});
final bool enabled;
final SurfaceTokens tokens;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Semantics(
button: true,
enabled: enabled,
label: 'Replace all',
child: ClideTappable(
onTap: enabled ? onTap : () {},
builder: (context, hovered, _) => Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
decoration: BoxDecoration(
color: enabled && hovered ? tokens.listItemHoverBackground : null,
border: Border.all(color: tokens.buttonBorder),
borderRadius: BorderRadius.circular(4),
),
child: ClideText(
'Replace all',
fontSize: clideFontCaption,
color: enabled ? tokens.sidebarForeground : tokens.globalTextMuted,
),
),
),
);
}
}
class _MessageDialog extends StatelessWidget {
const _MessageDialog({required this.title, required this.body, required this.dismiss});
final String title;
final String body;
final void Function([Object?]) dismiss;
@override
Widget build(BuildContext context) {
final tokens = ClideTheme.of(context).surface;
return _DialogFrame(
tokens: tokens,
children: [
ClideText(title, color: tokens.dropdownForeground),
const SizedBox(height: 8),
ClideText(body, fontSize: clideFontCaption, color: tokens.globalTextMuted),
const SizedBox(height: 12),
Align(
alignment: Alignment.centerRight,
child: _DialogButton(label: 'OK', tokens: tokens, onTap: () => dismiss()),
),
],
);
}
}
class _ConfirmDialog extends StatelessWidget {
const _ConfirmDialog({required this.body, required this.dismiss});
final String body;
final void Function([bool?]) dismiss;
@override
Widget build(BuildContext context) {
final tokens = ClideTheme.of(context).surface;
return _DialogFrame(
tokens: tokens,
children: [
ClideText(body, color: tokens.dropdownForeground),
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
_DialogButton(label: 'Cancel', tokens: tokens, onTap: () => dismiss(false)),
const SizedBox(width: 8),
_DialogButton(label: 'Confirm', tokens: tokens, onTap: () => dismiss(true)),
],
),
],
);
}
}
class _DialogFrame extends StatelessWidget {
const _DialogFrame({required this.tokens, required this.children});
final SurfaceTokens tokens;
final List<Widget> children;
@override
Widget build(BuildContext context) {
return Container(
width: 360,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: tokens.dropdownBackground,
border: Border.all(color: tokens.modalSurfaceBorder),
borderRadius: BorderRadius.circular(6),
),
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: children),
);
}
}
class _DialogButton extends StatelessWidget {
const _DialogButton({required this.label, required this.tokens, required this.onTap});
final String label;
final SurfaceTokens tokens;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Semantics(
button: true,
label: label,
child: ClideTappable(
onTap: onTap,
builder: (context, hovered, _) => Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: hovered ? tokens.listItemHoverBackground : null,
border: Border.all(color: tokens.buttonBorder),
borderRadius: BorderRadius.circular(4),
),
child: ClideText(label, fontSize: clideFontCaption, color: tokens.sidebarForeground),
),
),
);
}
}