diff --git a/src/plugins/cmakeprojectmanager/cmakeformatter.cpp b/src/plugins/cmakeprojectmanager/cmakeformatter.cpp index 9128adccad1..38e9f0cb32c 100644 --- a/src/plugins/cmakeprojectmanager/cmakeformatter.cpp +++ b/src/plugins/cmakeprojectmanager/cmakeformatter.cpp @@ -97,7 +97,11 @@ public: Core::Command *cmd = ActionManager::registerAction(&formatFile, Constants::CMAKEFORMATTER_ACTION_ID); connect(&formatFile, &QAction::triggered, this, [this] { - TextEditor::formatCurrentFile(formatCommand()); + auto command = formatCommand(); + if (auto editor = EditorManager::currentEditor()) + extendCommandWithConfigs(command, editor->document()->filePath()); + + TextEditor::formatCurrentFile(command); }); ActionManager::actionContainer(Constants::CMAKEFORMATTER_MENU_ID)->addAction(cmd); @@ -142,6 +146,46 @@ public: return cmd; } + static FilePaths formatConfigFiles(const FilePath &dir) + { + if (dir.isEmpty()) + return FilePaths(); + + return filtered(transform({".cmake-format", + ".cmake-format.py", + ".cmake-format.json", + ".cmake-format.yaml", + "cmake-format.py", + "cmake-format.json", + "cmake-format.yaml"}, + [dir](const QString &fileName) { + return dir.pathAppended(fileName); + }), + &FilePath::exists); + } + + static FilePaths findConfigs(const FilePath &fileName) + { + FilePath parentDirectory = fileName.parentDir(); + while (parentDirectory.exists()) { + FilePaths configFiles = formatConfigFiles(parentDirectory); + if (!configFiles.isEmpty()) + return configFiles; + + parentDirectory = parentDirectory.parentDir(); + } + return FilePaths(); + } + + static void extendCommandWithConfigs(TextEditor::Command &command, const FilePath &source) + { + const FilePaths configFiles = findConfigs(source); + if (!configFiles.isEmpty()) { + command.addOption("--config-files"); + command.addOptions(Utils::transform(configFiles, &FilePath::nativePath)); + } + } + FilePathAspect command{this}; bool haveValidFormatCommand{false}; BoolAspect autoFormatOnSave{this}; @@ -199,8 +243,10 @@ void CMakeFormatterSettings::applyIfNecessary(IDocument *document) const IEditor *currentEditor = EditorManager::currentEditor(); IEditor *editor = editors.contains(currentEditor) ? currentEditor : editors.first(); - if (auto widget = TextEditorWidget::fromEditor(editor)) + if (auto widget = TextEditorWidget::fromEditor(editor)) { + extendCommandWithConfigs(command, editor->document()->filePath()); TextEditor::formatEditor(widget, command); + } } CMakeFormatterSettings &formatterSettings()