Sources/Orgstar/ReplaceInFilesSheet.swift

c2d503b97e80b560fda12d61ecc99864f2a18a25
orgstar/Sources/Orgstar/ReplaceInFilesSheet.swift

173 lines · 8242 bytes

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