Files
MyGolandRelease/internal/app/replace.go
T
zerorigin a80c0f886a MyGoland 首次提交:Go 轻量 IDE
- 编辑器:多标签、语法高亮、gopls 全套(补全/诊断/跳转/重命名/代码动作/内联提示/签名大纲)
- 调试:Delve DAP(断点/条件断点/变量树/表达式求值/goroutine 列表)
- 测试:结果树、覆盖率行着色、失败跳源码、-run 精确运行、行号可跑标记
- Git:状态着色、选择性暂存提交、pull/push、历史并排对比
- 本地历史 + 自动快照 + 崩溃恢复、会话/光标恢复
- 全局搜索替换(预览+确认,GBK 安全)、多终端、gopls 崩溃自愈
- 设计文档与验证记录见 docs/plans/
2026-11-04 16:37:05 +08:00

201 lines
6.1 KiB
Go

package app
// 全局搜索替换:预览 + 确认两步走。
//
// 文本来源分两类,规则不同:
// - 打开中的文件:以**缓冲区**为准(未保存的改动也算),替换落在缓冲区上,
// 保持未保存状态走一步撤销——绝不绕过缓冲区直接写盘,否则一保存就把
// 替换结果盖掉了;
// - 没打开的文件:读盘 → 按原编码解码 → 替换 → 按原编码写回(GBK 配置
// 改完还是 GBK)。
//
// 匹配规则与全局搜索共用 buildReplaceRe(正则/大小写/整词同一套开关)。
import (
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"github.com/egoist/mygo/ui/editor"
)
// buildReplaceRe 与搜索的 buildMatcher 同一套装配规则,但返回正则本体——
// 替换要用 FindAllStringIndex 和 ExpandString,一个布尔函数不够。
func buildReplaceRe(query string, o searchOpts) (*regexp.Regexp, error) {
pat := query
if !o.useRegex {
pat = regexp.QuoteMeta(pat)
}
// 整词边界只加在 ASCII 词首尾上,理由见 buildMatcher。
if o.wholeWord && asciiWordEnds(query) {
pat = `\b(?:` + pat + `)\b`
}
if !o.matchCase {
pat = "(?i)" + pat
}
return regexp.Compile(pat)
}
// replaceInText 按行应用替换,返回新文本与替换次数。
//
// 逐行走是因为搜索的语义就是按行(^ $ 锚在行上),替换必须同语义,
// 不然「搜得到换不掉」比搜不到更气人。行结构原样保留,CRLF 不受影响。
// replacement 在正则模式下支持 $1 这类分组引用——所以必须用
// SubmatchIndex 拿到分组位置,FindAllStringIndex 只有整匹配,
// ExpandString 会把 $1 展开成空串。
func replaceInText(text string, re *regexp.Regexp, replacement string) (string, int) {
lines := strings.Split(text, "\n")
total := 0
for i, line := range lines {
ms := re.FindAllStringSubmatchIndex(line, -1)
if len(ms) == 0 {
continue
}
total += len(ms)
var b strings.Builder
last := 0
for _, m := range ms {
b.WriteString(line[last:m[0]])
b.Write(re.ExpandString(nil, replacement, line, m))
last = m[1]
}
b.WriteString(line[last:])
lines[i] = b.String()
}
return strings.Join(lines, "\n"), total
}
// fileReplace 是计划里的一个文件。
type fileReplace struct {
Abs string
Rel string // 仓库相对路径,正斜杠,给人看
// Count 是预览时算出的替换处数;确认时以实际执行为准
//(预览和确认之间缓冲区可能又变了)。
Count int
}
// replacePlan 是一次替换的预览结果。
type replacePlan struct {
Files []fileReplace
Total int
Truncated bool // 超出文件数上限,只列了一部分
}
// replacePlanCap 是预览最多列出的文件数,防止失控的工作区把面板撑爆。
const replacePlanCap = 400
// buildReplacePlan 算一遍替换计划(只读,不写任何东西)。
// openTexts 是打开文件「绝对路径 → 缓冲区文本」的快照,由调用方在主线程收好;
// 其余文件在这里读盘。编码不是 UTF-8 的文件也参与:decodeFile 能解 GBK/UTF-16。
func (a *App) buildReplacePlan(openTexts map[string]string, query, replacement string, o searchOpts) (replacePlan, error) {
re, err := buildReplaceRe(query, o)
if err != nil {
return replacePlan{}, err
}
var plan replacePlan
seen := map[string]bool{}
for path, text := range openTexts {
if n := countReplace(re, text, replacement); n > 0 {
plan.Files = append(plan.Files, fileReplace{Abs: path, Rel: a.relOf(path), Count: n})
plan.Total += n
}
seen[path] = true
}
for _, rel := range a.workspaceFiles() {
if len(plan.Files) >= replacePlanCap {
plan.Truncated = true
break
}
abs := filepath.Join(a.root, filepath.FromSlash(rel))
if seen[abs] {
continue
}
info, err := os.Stat(abs)
if err != nil || info.Size() > 512*1024 {
continue
}
data, err := os.ReadFile(abs)
if err != nil {
continue
}
text, _, ok := decodeFile(data)
if !ok {
continue // 不是文本,不碰
}
if n := countReplace(re, text, replacement); n > 0 {
plan.Files = append(plan.Files, fileReplace{Abs: abs, Rel: rel, Count: n})
plan.Total += n
}
}
sort.Slice(plan.Files, func(i, j int) bool { return plan.Files[i].Rel < plan.Files[j].Rel })
return plan, nil
}
// countReplace 算替换处数。
func countReplace(re *regexp.Regexp, text, replacement string) int {
_, n := replaceInText(text, re, replacement)
return n
}
// relOf 把绝对路径转成给人看的相对显示(越出根就原样给)。
func (a *App) relOf(abs string) string {
if rel, err := filepath.Rel(a.root, abs); err == nil {
return filepath.ToSlash(rel)
}
return filepath.ToSlash(abs)
}
// applyReplacePlan 执行计划:打开的改缓冲区(一步撤销 + 同步 LSP),
// 其余按原编码写盘。必须在主线程调用(缓冲区编辑与 lspSync 的要求)。
// 返回替换处数与失败清单。
func (a *App) applyReplacePlan(query, replacement string, o searchOpts, files []fileReplace) (int, int, []string) {
re, err := buildReplaceRe(query, o)
if err != nil {
return 0, 0, []string{"匹配规则有误: " + err.Error()}
}
hits, nfiles := 0, 0
var failed []string
for _, f := range files {
if d := a.find(f.Abs); d != nil {
newText, n := replaceInText(d.buf.String(), re, replacement)
if n == 0 {
continue // 预览之后缓冲区又变了,这次没有可替换的
}
d.buf.Transact(func() {
d.buf.Edit(editor.Edit{Start: 0, End: d.buf.Len(), Text: newText})
})
a.lspSync(d)
hits += n
nfiles++
continue
}
data, err := os.ReadFile(f.Abs)
if err != nil {
failed = append(failed, f.Rel+": "+err.Error())
continue
}
text, enc, ok := decodeFile(data)
if !ok {
failed = append(failed, f.Rel+": 不是文本文件,已跳过")
continue
}
newText, n := replaceInText(text, re, replacement)
if n == 0 {
continue // 磁盘内容变了,没有可替换的
}
out, err := encodeFile(newText, enc)
if err == nil {
err = os.WriteFile(f.Abs, out, 0o644)
}
if err != nil {
failed = append(failed, f.Rel+": "+err.Error())
continue
}
hits += n
nfiles++
}
return hits, nfiles, failed
}