Sources/Orgstar/ReplaceInFilesSheet.swift

62e3c7dafd265558ed379cccd7ca5877f42fafec
orgstar/Sources/Orgstar/ReplaceInFilesSheet.swift

174 lines · 8265 bytes

  1import OrgApp
  2import OrgCore
  3import OrgPresentation
  4import SwiftUI
  5
  6/// Edit ▸ Find ▸ Replace in Files…, Org ▸ TODO and Tags ▸ Rename Tag… and Rename TODO Keyword…:
  7/// what to look for and where, then every change by file and line to untick, then apply.
  8struct ReplaceInFilesSheet: View {
  9    let kind: ReplaceKind
 10    let workspace: WorkspaceModel
 11    let session: DocumentSession
 12    /// Called with what was done, after applying.
 13    let done: (String) -> Void
 14    @State private var model: ReplaceInFiles
 15    @State private var find = ""
 16    @State private var replacement = ""
 17    @AppStorage("replaceRegexp") private var regexp = false
 18    @AppStorage("replaceCaseFold") private var caseFold = true
 19    @AppStorage("replaceCaseReplace") private var caseReplace = true
 20    @State private var includeConfig = true
 21    /// A root's path, or empty for every folder.
 22    @State private var scope = ""
 23    @Environment(\.orgTheme) private var theme
 24    @Environment(\.dismiss) private var dismiss
 25
 26    init(kind: ReplaceKind, workspace: WorkspaceModel, session: DocumentSession, initial: String = "", done: @escaping (String) -> Void) {
 27        self.kind = kind
 28        self.workspace = workspace
 29        self.session = session
 30        self.done = done
 31        _model = State(initialValue: ReplaceInFiles(session: session, workspace: workspace))
 32        _find = State(initialValue: initial)
 33    }
 34
 35    var body: some View {
 36        VStack(alignment: .leading, spacing: 12) {
 37            Text(kind.title).font(.headline)
 38            form
 39            Divider()
 40            results
 41            HStack {
 42                Text(summary).foregroundStyle(.secondary)
 43                Spacer()
 44                Button("Close") { model.cancel(); dismiss() }
 45                    .keyboardShortcut(.cancelAction)
 46                Button(kind.applyTitle) {
 47                    done(model.apply())
 48                    dismiss()
 49                }
 50                .disabled(model.isSearching || (model.tickedCount == 0 && !(model.configChange != nil && model.changesConfig)))
 51            }
 52        }
 53        .padding()
 54        .frame(minWidth: 640, idealWidth: 760, minHeight: 460, idealHeight: 560)
 55        // Which headings a keyword rename changes depends on it, so the search runs again.
 56        .onChange(of: includeConfig) { if model.mode != nil, !find.isEmpty { search() } }
 57        #if !APPSTORE
 58        .onAppear {
 59            // Scripted runs answer the two fields and search, for the snapshot.
 60            let answers = DevelopmentHooks.answers
 61            guard answers.count >= 2 else { return }
 62            find = answers[0]
 63            replacement = answers[1]
 64            search()
 65        }
 66        #endif
 67    }
 68
 69    @ViewBuilder
 70    private var form: some View {
 71        Form {
 72            switch kind {
 73            case .replace:
 74                TextField("Find:", text: $find, prompt: regexp ? Text("Regular expression") : Text("Text"))
 75                TextField("Replace with:", text: $replacement, prompt: regexp ? Text("\\1 or $1 for a group") : Text("Text"))
 76                VStack(alignment: .leading, spacing: 4) {
 77                    Toggle("Regular expression", isOn: $regexp)
 78                    Toggle("Ignore case when the search is lower case", isOn: $caseFold)
 79                        .help("case-fold-search: a search with an upper-case letter matches case exactly")
 80                    Toggle("Keep each match's case", isOn: $caseReplace)
 81                        .help("case-replace: FOO becomes BAR and Foo becomes Bar")
 82                        .disabled(!caseFold)
 83                }
 84            case .renameTag:
 85                LabeledContent("Tag:") { nameField($find, suggestions: knownTags) }
 86                TextField("New name:", text: $replacement)
 87                Toggle("Also rename it in org-tag-alist in config.toml", isOn: $includeConfig)
 88            case .renameKeyword:
 89                LabeledContent("Keyword:") { nameField($find, suggestions: knownKeywords) }
 90                TextField("New name:", text: $replacement)
 91                Toggle("Also rename it in org-todo-keywords in config.toml", isOn: $includeConfig)
 92            }
 93            HStack {
 94                Picker("In:", selection: $scope) {
 95                    Text("All Folders").tag("")
 96                    ForEach(workspace.rootPaths, id: \.self) { root in
 97                        Text(verbatim: (root as NSString).lastPathComponent).tag(root)
 98                    }
 99                }
100                .fixedSize()
101                Spacer()
102                if model.isSearching {
103                    ProgressView(value: Double(model.progress.done), total: Double(max(1, model.progress.total)))
104                        .frame(width: 160)
105                    Button("Stop") { model.cancel() }
106                } else {
107                    Button("Find") { search() }
108                        .keyboardShortcut(.defaultAction)
109                        .disabled(find.isEmpty || (kind != .replace && replacement.isEmpty))
110                }
111            }
112        }
113    }
114
115    @ViewBuilder
116    private var results: some View {
117        if let problem = model.problem {
118            ContentUnavailableView(problem, systemImage: "exclamationmark.triangle")
119                .frame(maxHeight: .infinity)
120        } else if model.files.isEmpty && !(model.configChange != nil && model.changesConfig) {
121            if model.mode == nil || model.isSearching {
122                Color.clear.frame(maxHeight: .infinity)
123            } else {
124                ContentUnavailableView(String(localized: "No Matches", comment: "Replace in Files: the search found nothing"), systemImage: "magnifyingglass")
125                    .frame(maxHeight: .infinity)
126            }
127        } else {
128            ReplacePreview(model: model, removed: theme.color("todo") ?? .red, added: theme.color("done") ?? .green)
129                .frame(maxHeight: .infinity)
130        }
131    }
132
133    private var summary: String {
134        if model.isSearching {
135            return String(localized: "Searched \(model.progress.done) of \(model.progress.total) files", comment: "Replace in Files: progress")
136        }
137        guard model.mode != nil, model.problem == nil else { return "" }
138        let base = String(localized: "\(model.tickedCount) of \(model.changeCount) changes; files: \(model.files.count)", comment: "Replace in Files: what applying does")
139        return model.wasCancelled ? base + " · " + String(localized: "Stopped", comment: "Replace in Files: the search was stopped") : base
140    }
141
142    private func nameField(_ text: Binding<String>, suggestions: [String]) -> some View {
143        HStack(spacing: 4) {
144            TextField("", text: text).labelsHidden()
145            Menu {
146                ForEach(suggestions, id: \.self) { name in Button(name) { text.wrappedValue = name } }
147            } label: {
148                Image(systemName: "chevron.down")
149            }
150            .menuIndicator(.hidden)
151            .fixedSize()
152            .disabled(suggestions.isEmpty)
153            .accessibilityLabel(Text("Choose", comment: "Rename: menu of the existing names"))
154        }
155    }
156
157    private var knownTags: [String] { ((try? workspace.index.tags()) ?? []).sorted { $0.localizedStandardCompare($1) == .orderedAscending } }
158
159    private var knownKeywords: [String] {
160        var names: [String] = []
161        let sequences = session.defaults.todoSequences + (session.document?.tree.settings.todoSequences ?? [])
162        for name in sequences.flatMap({ ($0.active + $0.done).map(\.name) }) where !names.contains(name) { names.append(name) }
163        return names
164    }
165
166    private func search() {
167        let mode: ReplaceInFiles.Mode = switch kind {
168        case .replace: .replace(TextReplace(pattern: find, replacement: replacement, isRegexp: regexp, caseFold: caseFold, caseReplace: caseReplace))
169        case .renameTag: .renameTag(from: find.trimmingCharacters(in: .whitespaces), to: replacement.trimmingCharacters(in: .whitespaces))
170        case .renameKeyword: .renameKeyword(from: find.trimmingCharacters(in: .whitespaces), to: replacement.trimmingCharacters(in: .whitespaces))
171        }
172        model.start(mode, scope: scope.isEmpty ? nil : scope, includeConfig: includeConfig)
173    }
174}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form