Repository: CodeEditApp/CodeEdit
File: CodeEdit/Features/Documents/Controllers/CodeEditDocumentController.swift (Swift)

Code before:
        display displayDocument: Bool,
        completionHandler: @escaping (NSDocument?, Bool, Error?) -> Void
    ) {
        super.openDocument(withContentsOf: url, display: displayDocument) { document, documentWasAlreadyOpen, error in

            if let document {
                self.addDocument(document)
            } else {
                let errorMessage = error?.localizedDescription ?? "unknown error"
                print("Unable to open document '\(url)': \(errorMessage)")
            }

            RecentProjectsStore.documentOpened(at: url)
            completionHandler(document, documentWasAlreadyOpen, error)
        }
    }

    override func removeDocument(_ document: NSDocument) {
        super.removeDocument(document)

        if let workspace = document as? WorkspaceDocument, let path = workspace.fileURL?.absoluteURL.path() {
            lspService.closeWorkspace(path)
        }

        if CodeEditDocumentController.shared.documents.isEmpty {
            switch Settings[\.general].reopenWindowAfterClose {
            case .showWelcomeWindow:
                // Opens the welcome window
                openWindow(sceneID: .welcome)
            case .quit:
                // Quits CodeEdit
                NSApplication.shared.terminate(nil)
            case .doNothing: break
            }
        }
    }
}

extension NSDocumentController {
    final func openDocument(onCompletion: @escaping (NSDocument?, Bool) -> Void, onCancel: @escaping () -> Void) {
        let dialog = NSOpenPanel()

        dialog.title = "Open Workspace or File"
        dialog.showsResizeIndicator = true
        dialog.showsHiddenFiles = false
        dialog.canChooseFiles = true
        dialog.canChooseDirectories = true

        dialog.begin { result in
            if result ==  NSApplication.ModalResponse.OK, let url = dialog.url {
                self.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in

Review comment (performance):
Are all opened documents stored in `documents`, or only those within opened workspaces? If it’s the former, this could lead to performance issues when working with multiple large projects, and then trying to open a file.

Code after:
        display displayDocument: Bool,
        completionHandler: @escaping (NSDocument?, Bool, Error?) -> Void
    ) {
        guard !openFileInExistingWorkspace(url: url) else {
            return
        }

        super.openDocument(withContentsOf: url, display: displayDocument) { document, documentWasAlreadyOpen, error in
            if let document {
                self.addDocument(document)
            } else {
                let errorMessage = error?.localizedDescription ?? "unknown error"
                print("Unable to open document '\(url)': \(errorMessage)")
            }

            RecentProjectsStore.documentOpened(at: url)
            completionHandler(document, documentWasAlreadyOpen, error)
        }
    }

    /// Attempt to open the file URL in an open workspace, finding the nearest workspace to open it in if possible.
    /// - Parameter url: The file URL to open.
    /// - Returns: True, if the document was opened in a workspace.
    private func openFileInExistingWorkspace(url: URL) -> Bool {
        guard !url.isFolder else { return false }
        let workspaces = documents.compactMap({ $0 as? WorkspaceDocument })

        // Check open workspaces for the file being opened. Sorted by shared components with the url so we
        // open the nearest workspace possible.
        for workspace in workspaces.sorted(by: {
            ($0.fileURL?.sharedComponents(url) ?? 0) > ($1.fileURL?.sharedComponents(url) ?? 0)
        }) {
            // createIfNotFound will still return `nil` if the files don't share a common ancestor.
            if let newFile = workspace.workspaceFileManager?.getFile(url.absolutePath, createIfNotFound: true) {
                workspace.editorManager?.openTab(item: newFile)
                workspace.showWindows()
                return true
            }
        }
        return false
    }

    override func removeDocument(_ document: NSDocument) {
        super.removeDocument(document)

        if let workspace = document as? WorkspaceDocument, let path = workspace.fileURL?.absoluteURL.path() {
            lspService.closeWorkspace(path)
        }

        if CodeEditDocumentController.shared.documents.isEmpty {
            switch Settings[\.general].reopenWindowAfterClose {