diff --git a/plugins/grepview/grepdialog.cpp b/plugins/grepview/grepdialog.cpp index 4ab17a2d79..66451c5623 100644 --- a/plugins/grepview/grepdialog.cpp +++ b/plugins/grepview/grepdialog.cpp @@ -1,582 +1,580 @@ /*************************************************************************** * Copyright 1999-2001 Bernd Gehrmann and the KDevelop Team * * bernd@kdevelop.org * * Copyright 2007 Dukju Ahn * * Copyright 2010 Julien Desgats * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "grepdialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "grepviewplugin.h" #include "grepoutputview.h" #include "grepfindthread.h" #include "greputil.h" using namespace KDevelop; namespace { inline QString allOpenFilesString() { return i18n("All Open Files"); } inline QString allOpenProjectsString() { return i18n("All Open Projects"); } inline QStringList template_desc() { return QStringList{ QStringLiteral("verbatim"), QStringLiteral("word"), QStringLiteral("assignment"), QStringLiteral("->MEMBER("), QStringLiteral("class::MEMBER("), QStringLiteral("OBJECT->member("), }; } inline QStringList template_str() { return QStringList{ QStringLiteral("%s"), QStringLiteral("\\b%s\\b"), QStringLiteral("\\b%s\\b\\s*=[^=]"), QStringLiteral("\\->\\s*\\b%s\\b\\s*\\("), QStringLiteral("([a-z0-9_$]+)\\s*::\\s*\\b%s\\b\\s*\\("), QStringLiteral("\\b%s\\b\\s*\\->\\s*([a-z0-9_$]+)\\s*\\("), }; } inline QStringList repl_template() { return QStringList{ QStringLiteral("%s"), QStringLiteral("%s"), QStringLiteral("%s = "), QStringLiteral("->%s("), QStringLiteral("\\1::%s("), QStringLiteral("%s->\\1("), }; } inline QStringList filepatterns() { return QStringList{ QStringLiteral("*.h,*.hxx,*.hpp,*.hh,*.h++,*.H,*.tlh,*.cuh,*.cpp,*.cc,*.C,*.c++,*.cxx,*.ocl,*.inl,*.idl,*.c,*.cu,*.m,*.mm,*.M,*.y,*.ypp,*.yxx,*.y++,*.l,*.txt,*.xml,*.rc"), QStringLiteral("*.cpp,*.cc,*.C,*.c++,*.cxx,*.ocl,*.inl,*.c,*.cu,*.m,*.mm,*.M"), QStringLiteral("*.h,*.hxx,*.hpp,*.hh,*.h++,*.H,*.tlh,*.cuh,*.idl"), QStringLiteral("*.adb"), QStringLiteral("*.cs"), QStringLiteral("*.f"), QStringLiteral("*.html,*.htm"), QStringLiteral("*.hs"), QStringLiteral("*.java"), QStringLiteral("*.js"), QStringLiteral("*.php,*.php3,*.php4"), QStringLiteral("*.pl"), QStringLiteral("*.pp,*.pas"), QStringLiteral("*.py"), QStringLiteral("*.js,*.css,*.yml,*.rb,*.rhtml,*.html.erb,*.rjs,*.js.rjs,*.rxml,*.xml.builder"), QStringLiteral("CMakeLists.txt,*.cmake"), QStringLiteral("*"), }; } inline QStringList excludepatterns() { return QStringList{ QStringLiteral("/CVS/,/SCCS/,/.svn/,/_darcs/,/build/,/.git/"), QString(), }; } ///Separator used to separate search paths. inline QString pathsSeparator() { return (QStringLiteral(";")); } ///Returns the chosen directories or files (only the top directories, not subfiles) QList getDirectoryChoice(const QString& text) { QList ret; if (text == allOpenFilesString()) { const auto openDocuments = ICore::self()->documentController()->openDocuments(); ret.reserve(openDocuments.size()); for (auto* doc : openDocuments) { ret << doc->url(); } } else if (text == allOpenProjectsString()) { const auto projects = ICore::self()->projectController()->projects(); ret.reserve(projects.size()); for (auto* project : projects) { ret << project->path().toUrl(); } } else { const QStringList semicolonSeparatedFileList = text.split(pathsSeparator()); if (!semicolonSeparatedFileList.isEmpty() && QFileInfo::exists(semicolonSeparatedFileList[0])) { // We use QFileInfo to make sure this is really a semicolon-separated file list, not a file containing // a semicolon in the name. ret.reserve(semicolonSeparatedFileList.size()); for (const QString& file : semicolonSeparatedFileList) { ret << QUrl::fromLocalFile(file).adjusted(QUrl::StripTrailingSlash); } } else { ret << QUrl::fromUserInput(text).adjusted(QUrl::StripTrailingSlash); } } return ret; } ///Check if all directories are part of a project bool directoriesInProject(const QString& dir) { - foreach (const QUrl& url, getDirectoryChoice(dir)) { + const auto urls = getDirectoryChoice(dir); + return std::all_of(urls.begin(), urls.end(), [&](const QUrl& url) { IProject *proj = ICore::self()->projectController()->findProjectForUrl(url); - if (!proj || !proj->path().toUrl().isLocalFile()) { - return false; - } - } - - return true; + return (proj && proj->path().toUrl().isLocalFile()); + }); } ///Max number of items in paths combo box. const int pathsMaxCount = 25; } GrepDialog::GrepDialog(GrepViewPlugin *plugin, QWidget *parent, bool show) : QDialog(parent), Ui::GrepWidget(), m_plugin(plugin), m_show(show) { setAttribute(Qt::WA_DeleteOnClose); // if we don't intend on showing the dialog, we can skip all UI setup if (!m_show) { return; } setWindowTitle( i18n("Find/Replace in Files") ); setupUi(this); adjustSize(); auto searchButton = buttonBox->button(QDialogButtonBox::Ok); Q_ASSERT(searchButton); searchButton->setText(i18nc("@action:button", "Search...")); searchButton->setIcon(QIcon::fromTheme(QStringLiteral("edit-find"))); connect(searchButton, &QPushButton::clicked, this, &GrepDialog::startSearch); connect(buttonBox, &QDialogButtonBox::rejected, this, &GrepDialog::reject); KConfigGroup cg = ICore::self()->activeSession()->config()->group( "GrepDialog" ); patternCombo->addItems( cg.readEntry("LastSearchItems", QStringList()) ); patternCombo->setInsertPolicy(QComboBox::InsertAtTop); templateTypeCombo->addItems(template_desc()); templateTypeCombo->setCurrentIndex( cg.readEntry("LastUsedTemplateIndex", 0) ); templateEdit->addItems( cg.readEntry("LastUsedTemplateString", template_str()) ); templateEdit->setEditable(true); templateEdit->setCompletionMode(KCompletion::CompletionPopup); KCompletion* comp = templateEdit->completionObject(); connect(templateEdit, QOverload::of(&KComboBox::returnPressed), comp, QOverload::of(&KCompletion::addItem)); for(int i=0; icount(); i++) comp->addItem(templateEdit->itemText(i)); replacementTemplateEdit->addItems( cg.readEntry("LastUsedReplacementTemplateString", repl_template()) ); replacementTemplateEdit->setEditable(true); replacementTemplateEdit->setCompletionMode(KCompletion::CompletionPopup); comp = replacementTemplateEdit->completionObject(); connect(replacementTemplateEdit, QOverload::of(&KComboBox::returnPressed), comp, QOverload::of(&KCompletion::addItem)); for(int i=0; icount(); i++) comp->addItem(replacementTemplateEdit->itemText(i)); regexCheck->setChecked(cg.readEntry("regexp", false )); caseSensitiveCheck->setChecked(cg.readEntry("case_sens", true)); searchPaths->setCompletionObject(new KUrlCompletion()); searchPaths->setAutoDeleteCompletionObject(true); QList projects = m_plugin->core()->projectController()->projects(); searchPaths->addItems(cg.readEntry("SearchPaths", QStringList(!projects.isEmpty() ? allOpenProjectsString() : QDir::homePath() ) )); searchPaths->setInsertPolicy(QComboBox::InsertAtTop); syncButton->setIcon(QIcon::fromTheme(QStringLiteral("dirsync"))); syncButton->setMenu(createSyncButtonMenu()); depthSpin->setValue(cg.readEntry("depth", -1)); limitToProjectCheck->setChecked(cg.readEntry("search_project_files", true)); filesCombo->addItems(cg.readEntry("file_patterns", filepatterns())); excludeCombo->addItems(cg.readEntry("exclude_patterns", excludepatterns()) ); connect(templateTypeCombo, QOverload::of(&KComboBox::activated), this, &GrepDialog::templateTypeComboActivated); connect(patternCombo, &QComboBox::editTextChanged, this, &GrepDialog::patternComboEditTextChanged); patternComboEditTextChanged( patternCombo->currentText() ); patternCombo->setFocus(); connect(searchPaths, QOverload::of(&KComboBox::activated), this, &GrepDialog::setSearchLocations); directorySelector->setIcon(QIcon::fromTheme(QStringLiteral("document-open"))); connect(directorySelector, &QPushButton::clicked, this, &GrepDialog::selectDirectoryDialog ); } void GrepDialog::selectDirectoryDialog() { const QString dirName = QFileDialog::getExistingDirectory( this, i18nc("@title:window", "Select directory to search in"), searchPaths->lineEdit()->text()); if (!dirName.isEmpty()) { setSearchLocations(dirName); } } void GrepDialog::addUrlToMenu(QMenu* menu, const QUrl& url) { QAction* action = menu->addAction(m_plugin->core()->projectController()->prettyFileName(url, KDevelop::IProjectController::FormatPlain)); action->setData(QVariant(url.toString(QUrl::PreferLocalFile))); connect(action, &QAction::triggered, this, &GrepDialog::synchronizeDirActionTriggered); } void GrepDialog::addStringToMenu(QMenu* menu, const QString& string) { QAction* action = menu->addAction(string); action->setData(QVariant(string)); connect(action, &QAction::triggered, this, &GrepDialog::synchronizeDirActionTriggered); } void GrepDialog::synchronizeDirActionTriggered(bool) { auto* action = qobject_cast(sender()); Q_ASSERT(action); setSearchLocations(action->data().toString()); } QMenu* GrepDialog::createSyncButtonMenu() { auto* ret = new QMenu(this); QSet hadUrls; IDocument *doc = m_plugin->core()->documentController()->activeDocument(); if ( doc ) { Path url = Path(doc->url()).parent(); // always add the current file's parent directory hadUrls.insert(url); addUrlToMenu(ret, url.toUrl()); url = url.parent(); while(m_plugin->core()->projectController()->findProjectForUrl(url.toUrl())) { if(hadUrls.contains(url)) break; hadUrls.insert(url); addUrlToMenu(ret, url.toUrl()); url = url.parent(); } } QVector otherProjectUrls; - foreach(IProject* project, m_plugin->core()->projectController()->projects()) - { + const auto projects = m_plugin->core()->projectController()->projects(); + for (IProject* project : projects) { if (!hadUrls.contains(project->path())) { otherProjectUrls.append(project->path().toUrl()); } } // sort the remaining project URLs alphabetically std::sort(otherProjectUrls.begin(), otherProjectUrls.end()); - foreach(const QUrl& url, otherProjectUrls) - { + for (const QUrl& url : qAsConst(otherProjectUrls)) { addUrlToMenu(ret, url); } ret->addSeparator(); addStringToMenu(ret, allOpenFilesString()); addStringToMenu(ret, allOpenProjectsString()); return ret; } GrepDialog::~GrepDialog() { } void GrepDialog::setVisible(bool visible) { QDialog::setVisible(visible && m_show); } void GrepDialog::closeEvent(QCloseEvent* closeEvent) { Q_UNUSED(closeEvent); if (!m_show) { return; } KConfigGroup cg = ICore::self()->activeSession()->config()->group( "GrepDialog" ); // memorize the last patterns and paths cg.writeEntry("LastSearchItems", qCombo2StringList(patternCombo)); cg.writeEntry("regexp", regexCheck->isChecked()); cg.writeEntry("depth", depthSpin->value()); cg.writeEntry("search_project_files", limitToProjectCheck->isChecked()); cg.writeEntry("case_sens", caseSensitiveCheck->isChecked()); cg.writeEntry("exclude_patterns", qCombo2StringList(excludeCombo)); cg.writeEntry("file_patterns", qCombo2StringList(filesCombo)); cg.writeEntry("LastUsedTemplateIndex", templateTypeCombo->currentIndex()); cg.writeEntry("LastUsedTemplateString", qCombo2StringList(templateEdit)); cg.writeEntry("LastUsedReplacementTemplateString", qCombo2StringList(replacementTemplateEdit)); cg.writeEntry("SearchPaths", qCombo2StringList(searchPaths)); cg.sync(); } void GrepDialog::templateTypeComboActivated(int index) { templateEdit->setCurrentItem( template_str().at(index), true ); replacementTemplateEdit->setCurrentItem( repl_template().at(index), true ); } void GrepDialog::setSettings(const GrepJobSettings& settings) { patternCombo->setEditText(settings.pattern); patternComboEditTextChanged(settings.pattern); m_settings.pattern = settings.pattern; limitToProjectCheck->setEnabled(settings.projectFilesOnly); limitToProjectLabel->setEnabled(settings.projectFilesOnly); m_settings.projectFilesOnly = settings.projectFilesOnly; // Note: everything else is set by a user } GrepJobSettings GrepDialog::settings() const { return m_settings; } void GrepDialog::historySearch(QVector &settingsHistory) { // clear the current settings history and pass it to a job list m_historyJobSettings.clear(); m_historyJobSettings.swap(settingsHistory); // check if anything is do be done and if all projects are loaded if (!m_historyJobSettings.empty() && !checkProjectsOpened()) { connect(KDevelop::ICore::self()->projectController(), &KDevelop::IProjectController::projectOpened, this, &GrepDialog::checkProjectsOpened); } } void GrepDialog::setSearchLocations(const QString& dir) { if (!dir.isEmpty()) { if (m_show) { if (QDir::isAbsolutePath(dir)) { static_cast(searchPaths->completionObject())->setDir( QUrl::fromLocalFile(dir) ); } if (searchPaths->contains(dir)) { searchPaths->removeItem(searchPaths->findText(dir)); } searchPaths->insertItem(0, dir); searchPaths->setCurrentItem(dir); if (searchPaths->count() > pathsMaxCount) { searchPaths->removeItem(searchPaths->count() - 1); } } else { m_settings.searchPaths = dir; } } m_settings.projectFilesOnly = directoriesInProject(dir); } void GrepDialog::patternComboEditTextChanged( const QString& text) { buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!text.isEmpty()); } bool GrepDialog::checkProjectsOpened() { // only proceed if all projects have been opened if (KDevelop::ICore::self()->activeSession()->config()->group("General Options").readEntry("Open Projects", QList()).count() != KDevelop::ICore::self()->projectController()->projects().count()) return false; - foreach (IProject* p, KDevelop::ICore::self()->projectController()->projects()) { + const auto projects = KDevelop::ICore::self()->projectController()->projects(); + for (IProject* p : projects) { if (!p->isReady()) return false; } // do the grep jobs one by one connect(m_plugin, &GrepViewPlugin::grepJobFinished, this, &GrepDialog::nextHistory); QTimer::singleShot(0, this, [=]() {nextHistory(true);}); return true; } void GrepDialog::nextHistory(bool next) { if (next && !m_historyJobSettings.empty()) { m_settings = m_historyJobSettings.takeFirst(); startSearch(); } else { close(); } } bool GrepDialog::isPartOfChoice(const QUrl& url) const { - foreach(const QUrl& choice, getDirectoryChoice(m_settings.searchPaths)) { + const auto choices = getDirectoryChoice(m_settings.searchPaths); + for (const QUrl& choice : choices) { if(choice.isParentOf(url) || choice == url) return true; } return false; } void GrepDialog::startSearch() { // if m_show is false, all settings are fixed in m_settings if (m_show) updateSettings(); const QStringList include = GrepFindFilesThread::parseInclude(m_settings.files); const QStringList exclude = GrepFindFilesThread::parseExclude(m_settings.exclude); // search for unsaved documents QList unsavedFiles; - foreach(IDocument* doc, ICore::self()->documentController()->openDocuments()) - { + const auto documents = ICore::self()->documentController()->openDocuments(); + for (IDocument* doc : documents) { QUrl docUrl = doc->url(); if (doc->state() != IDocument::Clean && isPartOfChoice(docUrl) && QDir::match(include, docUrl.fileName()) && !QDir::match(exclude, docUrl.toLocalFile()) ) { unsavedFiles << doc; } } if(!ICore::self()->documentController()->saveSomeDocuments(unsavedFiles)) { close(); return; } const QString descriptionOrUrl(m_settings.searchPaths); QList choice = getDirectoryChoice(descriptionOrUrl); QString description = descriptionOrUrl; // Shorten the description if(descriptionOrUrl != allOpenFilesString() && descriptionOrUrl != allOpenProjectsString()) { auto prettyFileName = [](const QUrl& url) { return ICore::self()->projectController()->prettyFileName(url, KDevelop::IProjectController::FormatPlain); }; if (choice.size() > 1) { description = i18np("%2, and %1 more item", "%2, and %1 more items", choice.size() - 1, prettyFileName(choice[0])); } else if (!choice.isEmpty()) { description = prettyFileName(choice[0]); } } GrepOutputView *toolView = (GrepOutputView*)ICore::self()->uiController()->findToolView( i18n("Find/Replace in Files"), m_plugin->toolViewFactory(), m_settings.fromHistory ? IUiController::Create : IUiController::CreateAndRaise); if (m_settings.fromHistory) { // when restored from history, only display the parameters toolView->renewModel(m_settings, i18n("Search \"%1\" in %2", m_settings.pattern, description)); emit m_plugin->grepJobFinished(true); } else { GrepOutputModel* outputModel = toolView->renewModel(m_settings, i18n("Search \"%1\" in %2 (at time %3)", m_settings.pattern, description, QTime::currentTime().toString(QStringLiteral("hh:mm")))); GrepJob* job = m_plugin->newGrepJob(); connect(job, &GrepJob::showErrorMessage, toolView, &GrepOutputView::showErrorMessage); //the GrepOutputModel gets the 'showMessage' signal to store it and forward //it to toolView connect(job, &GrepJob::showMessage, outputModel, &GrepOutputModel::showMessageSlot); connect(outputModel, &GrepOutputModel::showMessage, toolView, &GrepOutputView::showMessage); connect(toolView, &GrepOutputView::outputViewIsClosed, job, [=]() {job->kill();}); job->setOutputModel(outputModel); job->setDirectoryChoice(choice); job->setSettings(m_settings); ICore::self()->runController()->registerJob(job); } m_plugin->rememberSearchDirectory(descriptionOrUrl); // if m_show is false, the dialog is closed somewhere else if (m_show) close(); } void GrepDialog::updateSettings() { if (limitToProjectCheck->isEnabled()) m_settings.projectFilesOnly = limitToProjectCheck->isChecked(); m_settings.caseSensitive = caseSensitiveCheck->isChecked(); m_settings.regexp = regexCheck->isChecked(); m_settings.depth = depthSpin->value(); m_settings.pattern = patternCombo->currentText(); m_settings.searchTemplate = templateEdit->currentText().isEmpty() ? QStringLiteral("%s") : templateEdit->currentText(); m_settings.replacementTemplate = replacementTemplateEdit->currentText(); m_settings.files = filesCombo->currentText(); m_settings.exclude = excludeCombo->currentText(); m_settings.searchPaths = searchPaths->currentText(); } diff --git a/plugins/grepview/grepfindthread.cpp b/plugins/grepview/grepfindthread.cpp index e8e0c70524..714512d3de 100644 --- a/plugins/grepview/grepfindthread.cpp +++ b/plugins/grepview/grepfindthread.cpp @@ -1,178 +1,176 @@ #include "grepfindthread.h" #include "debug.h" #include #include #include #include #include #include #include using KDevelop::IndexedString; /** * @return Return true in case @p url is in @p dir within a maximum depth of @p maxDepth */ static bool isInDirectory(const QUrl& url, const QUrl& dir, int maxDepth) { QUrl folderUrl = url.adjusted(QUrl::RemoveFilename); int currentLevel = maxDepth; while(currentLevel > 0) { folderUrl = folderUrl.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash); if ( folderUrl == dir.adjusted(QUrl::StripTrailingSlash) ) { return true; } currentLevel--; } return false; } // the abort parameter must be volatile so that it // is evaluated every time - optimization might prevent that static QList thread_getProjectFiles(const QUrl& dir, int depth, const QStringList& include, const QStringList& exlude, volatile bool &abort) { ///@todo This is not thread-safe! KDevelop::IProject *project = KDevelop::ICore::self()->projectController()->findProjectForUrl( dir ); QList res; if(!project) return res; const QSet fileSet = project->fileSet(); for (const IndexedString& item : fileSet) { if(abort) break; QUrl url = item.toUrl(); if( url != dir ) { if ( depth == 0 ) { if ( url.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash) != dir.adjusted(QUrl::StripTrailingSlash) ) { continue; } } else if ( !dir.isParentOf(url) ) { continue; } else if ( depth > 0 ) { // To ensure the current file is within the defined depth limit, navigate up the tree for as many levels // as the depth value, trying to find "dir", which is the project folder. If after all the loops there // is no match, it means the current file is deeper down the project tree than the limit depth, and so // it must be skipped. if(!isInDirectory(url, dir, depth)) continue; } } if( QDir::match(include, url.fileName()) && !QDir::match(exlude, url.toLocalFile()) ) res << url; } return res; } static QList thread_findFiles(const QDir& dir, int depth, const QStringList& include, const QStringList& exclude, volatile bool &abort) { QFileInfoList infos = dir.entryInfoList(include, QDir::NoDotAndDotDot|QDir::Files|QDir::Readable); if(!QFileInfo(dir.path()).isDir()) infos << QFileInfo(dir.path()); QList dirFiles; - foreach(const QFileInfo &currFile, infos) - { + for (const QFileInfo& currFile : qAsConst(infos)) { QString currName = currFile.canonicalFilePath(); if(!QDir::match(exclude, currName)) dirFiles << QUrl::fromLocalFile(currName); } if(depth != 0) { static const QDir::Filters dirFilter = QDir::NoDotAndDotDot|QDir::AllDirs|QDir::Readable|QDir::NoSymLinks; - foreach(const QFileInfo &currDir, dir.entryInfoList(QStringList(), dirFilter)) - { + const auto dirs = dir.entryInfoList(QStringList(), dirFilter); + for (const QFileInfo& currDir : dirs) { if(abort) break; QString canonical = currDir.canonicalFilePath(); if (!canonical.startsWith(dir.canonicalPath())) continue; if ( depth > 0 ) { depth--; } dirFiles << thread_findFiles(canonical, depth, include, exclude, abort); } } return dirFiles; } GrepFindFilesThread::GrepFindFilesThread(QObject* parent, const QList& startDirs, int depth, const QString& pats, const QString& excl, bool onlyProject) : QThread(parent) , m_startDirs(startDirs) , m_patString(pats) , m_exclString(excl) , m_depth(depth) , m_project(onlyProject) , m_tryAbort(false) { setTerminationEnabled(false); } void GrepFindFilesThread::tryAbort() { m_tryAbort = true; } bool GrepFindFilesThread::triesToAbort() const { return m_tryAbort; } void GrepFindFilesThread::run() { QStringList include = GrepFindFilesThread::parseInclude(m_patString); QStringList exclude = GrepFindFilesThread::parseExclude(m_exclString); qCDebug(PLUGIN_GREPVIEW) << "running with start dir" << m_startDirs; - foreach(const QUrl& directory, m_startDirs) - { + for (const QUrl& directory : qAsConst(m_startDirs)) { if(m_project) m_files += thread_getProjectFiles(directory, m_depth, include, exclude, m_tryAbort); else { m_files += thread_findFiles(directory.toLocalFile(), m_depth, include, exclude, m_tryAbort); } } } QList GrepFindFilesThread::files() const { auto tmpList = QList::fromSet(m_files.toSet()); std::sort(tmpList.begin(), tmpList.end()); return tmpList; } QStringList GrepFindFilesThread::parseExclude(const QString& excl) { QStringList exclude; // Split around commas or spaces const auto excludesList = excl.split(QRegExp(QStringLiteral(",|\\s")), QString::SkipEmptyParts); exclude.reserve(excludesList.size()); for (const auto& sub : excludesList) { exclude << QStringLiteral("*%1*").arg(sub); } return exclude; } QStringList GrepFindFilesThread::parseInclude(const QString& inc) { // Split around commas or spaces return inc.split(QRegExp(QStringLiteral(",|\\s")), QString::SkipEmptyParts); } diff --git a/plugins/grepview/grepoutputview.cpp b/plugins/grepview/grepoutputview.cpp index d3186d2386..d80b8ff6df 100644 --- a/plugins/grepview/grepoutputview.cpp +++ b/plugins/grepview/grepoutputview.cpp @@ -1,485 +1,485 @@ /************************************************************************** * Copyright 2010 Silvère Lestang * * Copyright 2010 Julien Desgats * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "grepoutputview.h" #include "grepoutputmodel.h" #include "grepoutputdelegate.h" #include "ui_grepoutputview.h" #include "grepviewplugin.h" #include "grepdialog.h" #include "greputil.h" #include "grepjob.h" #include "debug.h" #include #include #include #include #include #include #include #include #include using namespace KDevelop; GrepOutputViewFactory::GrepOutputViewFactory(GrepViewPlugin* plugin) : m_plugin(plugin) {} QWidget* GrepOutputViewFactory::create(QWidget* parent) { return new GrepOutputView(parent, m_plugin); } Qt::DockWidgetArea GrepOutputViewFactory::defaultPosition() { return Qt::BottomDockWidgetArea; } QString GrepOutputViewFactory::id() const { return QStringLiteral("org.kdevelop.GrepOutputView"); } const int GrepOutputView::HISTORY_SIZE = 5; namespace { enum { GrepSettingsStorageItemCount = 10 }; } GrepOutputView::GrepOutputView(QWidget* parent, GrepViewPlugin* plugin) : QWidget(parent) , m_next(nullptr) , m_prev(nullptr) , m_collapseAll(nullptr) , m_expandAll(nullptr) , m_refresh(nullptr) , m_clearSearchHistory(nullptr) , m_statusLabel(nullptr) , m_plugin(plugin) { Ui::GrepOutputView::setupUi(this); setWindowTitle(i18nc("@title:window", "Find/Replace Output View")); setWindowIcon(QIcon::fromTheme(QStringLiteral("edit-find"), windowIcon())); m_prev = new QAction(QIcon::fromTheme(QStringLiteral("go-previous")), i18n("&Previous Item"), this); m_next = new QAction(QIcon::fromTheme(QStringLiteral("go-next")), i18n("&Next Item"), this); m_collapseAll = new QAction(QIcon::fromTheme(QStringLiteral("arrow-left-double")), i18n("C&ollapse All"), this); // TODO change icon m_expandAll = new QAction(QIcon::fromTheme(QStringLiteral("arrow-right-double")), i18n("&Expand All"), this); // TODO change icon updateButtonState(false); auto *separator = new QAction(this); separator->setSeparator(true); QAction *newSearchAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-find")), i18n("New &Search"), this); m_refresh = new QAction(QIcon::fromTheme(QStringLiteral("view-refresh")), i18n("Refresh"), this); m_refresh->setEnabled(false); m_clearSearchHistory = new QAction(QIcon::fromTheme(QStringLiteral("edit-clear-list")), i18n("Clear Search History"), this); m_clearSearchHistory->setEnabled(false); addAction(m_prev); addAction(m_next); addAction(m_collapseAll); addAction(m_expandAll); addAction(separator); addAction(newSearchAction); addAction(m_refresh); addAction(m_clearSearchHistory); separator = new QAction(this); separator->setSeparator(true); addAction(separator); auto *statusWidget = new QWidgetAction(this); m_statusLabel = new QLabel(this); statusWidget->setDefaultWidget(m_statusLabel); addAction(statusWidget); modelSelector->setEditable(false); modelSelector->setContextMenuPolicy(Qt::CustomContextMenu); connect(modelSelector, &KComboBox::customContextMenuRequested, this, &GrepOutputView::modelSelectorContextMenu); connect(modelSelector, QOverload::of(&KComboBox::currentIndexChanged), this, &GrepOutputView::changeModel); resultsTreeView->setItemDelegate(GrepOutputDelegate::self()); resultsTreeView->setRootIsDecorated(false); resultsTreeView->setHeaderHidden(true); resultsTreeView->setUniformRowHeights(false); resultsTreeView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); connect(m_prev, &QAction::triggered, this, &GrepOutputView::selectPreviousItem); connect(m_next, &QAction::triggered, this, &GrepOutputView::selectNextItem); connect(m_collapseAll, &QAction::triggered, this, &GrepOutputView::collapseAllItems); connect(m_expandAll, &QAction::triggered, this, &GrepOutputView::expandAllItems); connect(applyButton, &QPushButton::clicked, this, &GrepOutputView::onApply); connect(m_refresh, &QAction::triggered, this, &GrepOutputView::refresh); connect(m_clearSearchHistory, &QAction::triggered, this, &GrepOutputView::clearSearchHistory); KConfigGroup cg = ICore::self()->activeSession()->config()->group( "GrepDialog" ); replacementCombo->addItems( cg.readEntry("LastReplacementItems", QStringList()) ); replacementCombo->setInsertPolicy(QComboBox::InsertAtTop); applyButton->setIcon(QIcon::fromTheme(QStringLiteral("dialog-ok-apply"))); connect(replacementCombo, &KComboBox::editTextChanged, this, &GrepOutputView::replacementTextChanged); connect(replacementCombo, QOverload<>::of(&KComboBox::returnPressed), this, &GrepOutputView::onApply); connect(newSearchAction, &QAction::triggered, this, &GrepOutputView::showDialog); resultsTreeView->header()->setStretchLastSection(true); resultsTreeView->header()->setStretchLastSection(true); // read Find/Replace settings history const QStringList s = cg.readEntry("LastSettings", QStringList()); if (s.size() % GrepSettingsStorageItemCount != 0) { qCWarning(PLUGIN_GREPVIEW) << "Stored settings history has unexpected size:" << s; } else { m_settingsHistory.reserve(s.size() / GrepSettingsStorageItemCount); auto it = s.begin(); while (it != s.end()) { GrepJobSettings settings; settings.projectFilesOnly = ((it++)->toUInt() != 0); settings.caseSensitive = ((it++)->toUInt() != 0); settings.regexp = ((it++)->toUInt() != 0); settings.depth = (it++)->toInt(); settings.pattern = *(it++); settings.searchTemplate = *(it++); settings.replacementTemplate = *(it++); settings.files = *(it++); settings.exclude = *(it++); settings.searchPaths = *(it++); settings.fromHistory = true; m_settingsHistory << settings; } } // rerun the grep jobs with settings from the history auto* dlg = new GrepDialog(m_plugin, this, false); dlg->historySearch(m_settingsHistory); updateCheckable(); } void GrepOutputView::replacementTextChanged() { updateCheckable(); if (model()) { // see https://bugs.kde.org/show_bug.cgi?id=274902 - renewModel can trigger a call here without an active model updateApplyState(model()->index(0, 0), model()->index(0, 0)); } } GrepOutputView::~GrepOutputView() { KConfigGroup cg = ICore::self()->activeSession()->config()->group( "GrepDialog" ); cg.writeEntry("LastReplacementItems", qCombo2StringList(replacementCombo, true)); QStringList settingsStrings; settingsStrings.reserve(m_settingsHistory.size() * GrepSettingsStorageItemCount); - foreach (const GrepJobSettings & s, m_settingsHistory) { + for (const GrepJobSettings& s : qAsConst(m_settingsHistory)) { settingsStrings << QString::number(s.projectFilesOnly ? 1 : 0) << QString::number(s.caseSensitive ? 1 : 0) << QString::number(s.regexp ? 1 : 0) << QString::number(s.depth) << s.pattern << s.searchTemplate << s.replacementTemplate << s.files << s.exclude << s.searchPaths; } cg.writeEntry("LastSettings", settingsStrings); emit outputViewIsClosed(); } GrepOutputModel* GrepOutputView::renewModel(const GrepJobSettings& settings, const QString& description) { // clear oldest model while(modelSelector->count() >= GrepOutputView::HISTORY_SIZE) { QVariant var = modelSelector->itemData(GrepOutputView::HISTORY_SIZE - 1); qvariant_cast(var)->deleteLater(); modelSelector->removeItem(GrepOutputView::HISTORY_SIZE - 1); } while(m_settingsHistory.count() >= GrepOutputView::HISTORY_SIZE) { m_settingsHistory.removeFirst(); } replacementCombo->clearEditText(); auto* newModel = new GrepOutputModel(resultsTreeView); applyButton->setEnabled(false); // text may be already present newModel->setReplacement(replacementCombo->currentText()); connect(newModel, &GrepOutputModel::rowsRemoved, this, &GrepOutputView::rowsRemoved); connect(resultsTreeView, &QTreeView::activated, newModel, &GrepOutputModel::activate); connect(replacementCombo, &KComboBox::editTextChanged, newModel, &GrepOutputModel::setReplacement); connect(newModel, &GrepOutputModel::rowsInserted, this, &GrepOutputView::expandElements); connect(newModel, &GrepOutputModel::showErrorMessage, this, &GrepOutputView::showErrorMessage); connect(m_plugin, &GrepViewPlugin::grepJobFinished, this, &GrepOutputView::updateScrollArea); // appends new model to history modelSelector->insertItem(0, description, qVariantFromValue(newModel)); modelSelector->setCurrentIndex(0); m_settingsHistory.append(settings); updateCheckable(); return newModel; } GrepOutputModel* GrepOutputView::model() { return static_cast(resultsTreeView->model()); } void GrepOutputView::changeModel(int index) { if (model()) { disconnect(model(), &GrepOutputModel::showMessage, this, &GrepOutputView::showMessage); disconnect(model(), &GrepOutputModel::dataChanged, this, &GrepOutputView::updateApplyState); } replacementCombo->clearEditText(); //after deleting the whole search history, index is -1 if(index >= 0) { QVariant var = modelSelector->itemData(index); auto *resultModel = static_cast(qvariant_cast(var)); resultsTreeView->setModel(resultModel); resultsTreeView->expandAll(); connect(model(), &GrepOutputModel::showMessage, this, &GrepOutputView::showMessage); connect(model(), &GrepOutputModel::dataChanged, this, &GrepOutputView::updateApplyState); model()->showMessageEmit(); applyButton->setEnabled(model()->hasResults() && model()->getRootItem() && model()->getRootItem()->checkState() != Qt::Unchecked && !replacementCombo->currentText().isEmpty()); if(model()->hasResults()) expandElements(QModelIndex()); else { updateButtonState(false); } } updateCheckable(); updateApplyState(model()->index(0, 0), model()->index(0, 0)); m_refresh->setEnabled(true); m_clearSearchHistory->setEnabled(true); } void GrepOutputView::setMessage(const QString& msg, MessageType type) { if (type == Error) { QPalette palette = m_statusLabel->palette(); KColorScheme::adjustForeground(palette, KColorScheme::NegativeText, QPalette::WindowText); m_statusLabel->setPalette(palette); } else { m_statusLabel->setPalette(QPalette()); } m_statusLabel->setText(msg); } void GrepOutputView::showErrorMessage( const QString& errorMessage ) { setMessage(errorMessage, Error); } void GrepOutputView::showMessage( KDevelop::IStatus* , const QString& message ) { setMessage(message, Information); } void GrepOutputView::onApply() { if(model()) { Q_ASSERT(model()->rowCount()); // ask a confirmation before an empty string replacement if(replacementCombo->currentText().length() == 0 && KMessageBox::questionYesNo(this, i18n("Do you want to replace with an empty string?"), i18n("Start replacement")) == KMessageBox::No) { return; } setEnabled(false); model()->doReplacements(); setEnabled(true); } } void GrepOutputView::showDialog() { m_plugin->showDialog(true); } void GrepOutputView::refresh() { int index = modelSelector->currentIndex(); if (index >= 0) { QVariant var = modelSelector->currentData(); qvariant_cast(var)->deleteLater(); modelSelector->removeItem(index); QVector refresh_history({ m_settingsHistory.takeAt(m_settingsHistory.count() - 1 - index) }); refresh_history.first().fromHistory = false; auto* dlg = new GrepDialog(m_plugin, this, false); dlg->historySearch(refresh_history); } } void GrepOutputView::expandElements(const QModelIndex& index) { updateButtonState(true); resultsTreeView->expand(index); } void GrepOutputView::updateButtonState(bool enable) { m_prev->setEnabled(enable); m_next->setEnabled(enable); m_collapseAll->setEnabled(enable); m_expandAll->setEnabled(enable); } void GrepOutputView::selectPreviousItem() { if (!model()) { return; } QModelIndex prev_idx = model()->previousItemIndex(resultsTreeView->currentIndex()); if (prev_idx.isValid()) { resultsTreeView->setCurrentIndex(prev_idx); model()->activate(prev_idx); } } void GrepOutputView::selectNextItem() { if (!model()) { return; } QModelIndex next_idx = model()->nextItemIndex(resultsTreeView->currentIndex()); if (next_idx.isValid()) { resultsTreeView->setCurrentIndex(next_idx); model()->activate(next_idx); } } void GrepOutputView::collapseAllItems() { // Collapse everything resultsTreeView->collapseAll(); if (resultsTreeView->model()) { // Now reopen the first children, which correspond to the files. resultsTreeView->expand(resultsTreeView->model()->index(0, 0)); } } void GrepOutputView::expandAllItems() { resultsTreeView->expandAll(); } void GrepOutputView::rowsRemoved() { Q_ASSERT(model()); updateButtonState(model()->rowCount() > 0); } void GrepOutputView::updateApplyState(const QModelIndex& topLeft, const QModelIndex& bottomRight) { Q_UNUSED(bottomRight); if (!model() || !model()->hasResults()) { applyButton->setEnabled(false); return; } // we only care about the root item if(!topLeft.parent().isValid()) { applyButton->setEnabled(topLeft.data(Qt::CheckStateRole) != Qt::Unchecked && model()->itemsCheckable()); } } void GrepOutputView::updateCheckable() { if(model()) model()->makeItemsCheckable(!replacementCombo->currentText().isEmpty() || model()->itemsCheckable()); } void GrepOutputView::clearSearchHistory() { GrepJob *runningJob = m_plugin->grepJob(); if(runningJob) { connect(runningJob, &GrepJob::finished, this, [=]() {updateButtonState(false);}); runningJob->kill(); } while(modelSelector->count() > 0) { QVariant var = modelSelector->itemData(0); qvariant_cast(var)->deleteLater(); modelSelector->removeItem(0); } m_settingsHistory.clear(); applyButton->setEnabled(false); updateButtonState(false); m_refresh->setEnabled(false); m_clearSearchHistory->setEnabled(false); m_statusLabel->setText(QString()); } void GrepOutputView::modelSelectorContextMenu(const QPoint& pos) { QPoint globalPos = modelSelector->mapToGlobal(pos); QMenu myMenu(this); myMenu.addAction(m_clearSearchHistory); myMenu.exec(globalPos); } void GrepOutputView::updateScrollArea() { if (!model()) { return; } for (int col = 0; col < model()->columnCount(); ++col) resultsTreeView->resizeColumnToContents(col); } diff --git a/plugins/grepview/grepviewplugin.cpp b/plugins/grepview/grepviewplugin.cpp index d804f7d9b8..3a6abbc73e 100644 --- a/plugins/grepview/grepviewplugin.cpp +++ b/plugins/grepview/grepviewplugin.cpp @@ -1,242 +1,242 @@ /*************************************************************************** * Copyright 1999-2001 by Bernd Gehrmann * * bernd@kdevelop.org * * Copyright 2007 Dukju Ahn * * Copyright 2010 Benjamin Port * * Copyright 2010 Julien Desgats * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "grepviewplugin.h" #include "grepdialog.h" #include "grepoutputmodel.h" #include "grepoutputdelegate.h" #include "grepjob.h" #include "grepoutputview.h" #include "debug.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static QString patternFromSelection(const KDevelop::IDocument* doc) { if (!doc) return QString(); QString pattern; KTextEditor::Range range = doc->textSelection(); if( range.isValid() ) { pattern = doc->textDocument()->text( range ); } if( pattern.isEmpty() ) { pattern = doc->textWord(); } // Before anything, this removes line feeds from the // beginning and the end. int len = pattern.length(); if (len > 0 && pattern[0] == QLatin1Char('\n')) { pattern.remove(0, 1); len--; } if (len > 0 && pattern[len-1] == QLatin1Char('\n')) pattern.truncate(len-1); return pattern; } GrepViewPlugin::GrepViewPlugin( QObject *parent, const QVariantList & ) : KDevelop::IPlugin( QStringLiteral("kdevgrepview"), parent ), m_currentJob(nullptr) { setXMLFile(QStringLiteral("kdevgrepview.rc")); QDBusConnection::sessionBus().registerObject( QStringLiteral("/org/kdevelop/GrepViewPlugin"), this, QDBusConnection::ExportScriptableSlots ); QAction*action = actionCollection()->addAction(QStringLiteral("edit_grep")); action->setText(i18n("Find/Replace in Fi&les...")); actionCollection()->setDefaultShortcut( action, QKeySequence(QStringLiteral("Ctrl+Alt+F")) ); connect(action, &QAction::triggered, this, &GrepViewPlugin::showDialogFromMenu); action->setToolTip( i18n("Search for expressions over several files") ); action->setWhatsThis( i18n("Opens the 'Find/Replace in files' dialog. There you " "can enter a regular expression which is then " "searched for within all files in the directories " "you specify. Matches will be displayed, you " "can switch to a match directly. You can also do replacement.") ); action->setIcon(QIcon::fromTheme(QStringLiteral("edit-find"))); // instantiate delegate, it's supposed to be deleted via QObject inheritance new GrepOutputDelegate(this); m_factory = new GrepOutputViewFactory(this); core()->uiController()->addToolView(i18n("Find/Replace in Files"), m_factory); } GrepOutputViewFactory* GrepViewPlugin::toolViewFactory() const { return m_factory; } GrepViewPlugin::~GrepViewPlugin() { } void GrepViewPlugin::unload() { - foreach (const QPointer &p, m_currentDialogs) { + for (const QPointer& p : qAsConst(m_currentDialogs)) { if (p) { p->reject(); p->deleteLater(); } } core()->uiController()->removeToolView(m_factory); } void GrepViewPlugin::startSearch(const QString& pattern, const QString& directory, bool show) { m_directory = directory; showDialog(false, pattern, show); } KDevelop::ContextMenuExtension GrepViewPlugin::contextMenuExtension(KDevelop::Context* context, QWidget* parent) { KDevelop::ContextMenuExtension extension = KDevelop::IPlugin::contextMenuExtension(context, parent); if( context->type() == KDevelop::Context::ProjectItemContext ) { auto* ctx = static_cast(context); QList items = ctx->items(); // verify if there is only one folder selected if ((items.count() == 1) && (items.first()->folder())) { QAction* action = new QAction(i18n("Find/Replace in This Folder..."), parent); action->setIcon(QIcon::fromTheme(QStringLiteral("edit-find"))); m_contextMenuDirectory = items.at(0)->folder()->path().toLocalFile(); connect( action, &QAction::triggered, this, &GrepViewPlugin::showDialogFromProject); extension.addAction( KDevelop::ContextMenuExtension::ExtensionGroup, action ); } } if ( context->type() == KDevelop::Context::EditorContext ) { auto* econtext = static_cast(context); if ( econtext->view()->selection() ) { QAction* action = new QAction(QIcon::fromTheme(QStringLiteral("edit-find")), i18n("&Find/Replace in Files..."), parent); connect(action, &QAction::triggered, this, &GrepViewPlugin::showDialogFromMenu); extension.addAction(KDevelop::ContextMenuExtension::ExtensionGroup, action); } } if(context->type() == KDevelop::Context::FileContext) { auto* fcontext = static_cast(context); // TODO: just stat() or QFileInfo().isDir() for local files? should be faster than mime type checking QMimeType mimetype = QMimeDatabase().mimeTypeForUrl(fcontext->urls().at(0)); static const QMimeType directoryMime = QMimeDatabase().mimeTypeForName(QStringLiteral("inode/directory")); if (mimetype == directoryMime) { QAction* action = new QAction(i18n("Find/Replace in This Folder..."), parent); action->setIcon(QIcon::fromTheme(QStringLiteral("edit-find"))); m_contextMenuDirectory = fcontext->urls().at(0).toLocalFile(); connect( action, &QAction::triggered, this, &GrepViewPlugin::showDialogFromProject); extension.addAction( KDevelop::ContextMenuExtension::ExtensionGroup, action ); } } return extension; } void GrepViewPlugin::showDialog(bool setLastUsed, const QString& pattern, bool show) { // check if dialog pointers are still valid, remove them otherwise m_currentDialogs.removeAll(QPointer()); auto* dlg = new GrepDialog( this, core()->uiController()->activeMainWindow(), show ); m_currentDialogs << dlg; GrepJobSettings dlgSettings = dlg->settings(); KDevelop::IDocument* doc = core()->documentController()->activeDocument(); if(!pattern.isEmpty()) { dlgSettings.pattern = pattern; dlg->setSettings(dlgSettings); } else if(!setLastUsed) { QString pattern = patternFromSelection(doc); if (!pattern.isEmpty()) { dlgSettings.pattern = pattern; dlg->setSettings(dlgSettings); } } //if directory is empty then use a default value from the config file. if (!m_directory.isEmpty()) { dlg->setSearchLocations(m_directory); } if(show) dlg->show(); else{ dlg->startSearch(); dlg->deleteLater(); } } void GrepViewPlugin::showDialogFromMenu() { showDialog(); } void GrepViewPlugin::showDialogFromProject() { rememberSearchDirectory(m_contextMenuDirectory); showDialog(); } void GrepViewPlugin::rememberSearchDirectory(QString const & directory) { m_directory = directory; } GrepJob* GrepViewPlugin::newGrepJob() { if(m_currentJob != nullptr) { m_currentJob->kill(); } m_currentJob = new GrepJob(); connect(m_currentJob, &GrepJob::finished, this, &GrepViewPlugin::jobFinished); return m_currentJob; } GrepJob* GrepViewPlugin::grepJob() { return m_currentJob; } void GrepViewPlugin::jobFinished(KJob* job) { if(job == m_currentJob) { m_currentJob = nullptr; emit grepJobFinished(job->error() == KJob::NoError); } } diff --git a/plugins/grepview/tests/test_findreplace.cpp b/plugins/grepview/tests/test_findreplace.cpp index b89b40772e..27fcdb03a9 100644 --- a/plugins/grepview/tests/test_findreplace.cpp +++ b/plugins/grepview/tests/test_findreplace.cpp @@ -1,201 +1,199 @@ /*************************************************************************** * Copyright 1999-2001 Bernd Gehrmann and the KDevelop Team * * bernd@kdevelop.org * * Copyright 2010 Julien Desgats * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "test_findreplace.h" #include #include #include #include #include #include #include "../grepjob.h" #include "../grepviewplugin.h" #include "../grepoutputmodel.h" void FindReplaceTest::initTestCase() { KDevelop::AutoTestShell::init(); KDevelop::TestCore::initialize(KDevelop::Core::NoUi); } void FindReplaceTest::cleanupTestCase() { KDevelop::TestCore::shutdown(); } void FindReplaceTest::testFind_data() { QTest::addColumn("subject"); QTest::addColumn("search"); QTest::addColumn("matches"); QTest::newRow("Basic") << "foobar" << QRegExp("foo") << (MatchList() << Match(0, 0, 3)); QTest::newRow("Multiple matches") << "foobar\nbar\nbarfoo" << QRegExp("foo") << (MatchList() << Match(0, 0, 3) << Match(2, 3, 6)); QTest::newRow("Multiple on same line") << "foobarbaz" << QRegExp("ba") << (MatchList() << Match(0, 3, 5) << Match(0, 6, 8)); QTest::newRow("Multiple sticked together") << "foofoobar" << QRegExp("foo") << (MatchList() << Match(0, 0, 3) << Match(0, 3, 6)); QTest::newRow("RegExp (member call)") << "foo->bar ();\nbar();" << QRegExp("\\->\\s*\\b(bar)\\b\\s*\\(") << (MatchList() << Match(0, 3, 10)); // the matching must be started after the last previous match QTest::newRow("RegExp (greedy match)") << "foofooo" << QRegExp("[o]+") << (MatchList() << Match(0, 1, 3) << Match(0, 4, 7)); QTest::newRow("Matching EOL") << "foobar\nfoobar" << QRegExp("foo.*") << (MatchList() << Match(0, 0, 6) << Match(1, 0, 6)); QTest::newRow("Matching EOL (Windows style)") << "foobar\r\nfoobar" << QRegExp("foo.*") << (MatchList() << Match(0, 0, 6) << Match(1, 0, 6)); QTest::newRow("Empty lines handling") << "foo\n\n\n" << QRegExp("bar") << (MatchList()); QTest::newRow("Can match empty string (at EOL)") << "foobar\n" << QRegExp(".*") << (MatchList() << Match(0, 0, 6)); QTest::newRow("Matching empty string anywhere") << "foobar\n" << QRegExp("") << (MatchList()); } void FindReplaceTest::testFind() { QFETCH(QString, subject); QFETCH(QRegExp, search); QFETCH(MatchList, matches); QTemporaryFile file; QVERIFY(file.open()); file.write(subject.toUtf8()); file.close(); GrepOutputItem::List actualMatches = grepFile(file.fileName(), search); QCOMPARE(actualMatches.length(), matches.length()); for(int i=0; im_range.start().line(), matches[i].line); QCOMPARE(actualMatches[i].change()->m_range.start().column(), matches[i].start); QCOMPARE(actualMatches[i].change()->m_range.end().column(), matches[i].end); } // check that file has not been altered by grepFile QVERIFY(file.open()); QCOMPARE(QString(file.readAll()), subject); } void FindReplaceTest::testReplace_data() { QTest::addColumn("subject"); QTest::addColumn("searchPattern"); QTest::addColumn("searchTemplate"); QTest::addColumn("replace"); QTest::addColumn("replaceTemplate"); QTest::addColumn("result"); QTest::newRow("Raw replace") << (FileList() << File(QStringLiteral("myfile.txt"), QStringLiteral("some text\nreplacement\nsome other test\n")) << File(QStringLiteral("otherfile.txt"), QStringLiteral("some replacement text\n\n"))) << "replacement" << "%s" << "dummy" << "%s" << (FileList() << File(QStringLiteral("myfile.txt"), QStringLiteral("some text\ndummy\nsome other test\n")) << File(QStringLiteral("otherfile.txt"), QStringLiteral("some dummy text\n\n"))); // see bug: https://bugs.kde.org/show_bug.cgi?id=301362 QTest::newRow("LF character replace") << (FileList() << File(QStringLiteral("somefile.txt"), QStringLiteral("hello world\\n"))) << "\\\\n" << "%s" << "\\n\\n" << "%s" << (FileList() << File(QStringLiteral("somefile.txt"), QStringLiteral("hello world\\n\\n"))); QTest::newRow("Template replace") << (FileList() << File(QStringLiteral("somefile.h"), QStringLiteral("struct Foo {\n void setFoo(int foo);\n};")) << File(QStringLiteral("somefile.cpp"), QStringLiteral("instance->setFoo(0);\n setFoo(0); /*not replaced*/"))) << "setFoo" << "\\->\\s*\\b%s\\b\\s*\\(" << "setBar" << "->%s(" << (FileList() << File(QStringLiteral("somefile.h"), QStringLiteral("struct Foo {\n void setFoo(int foo);\n};")) << File(QStringLiteral("somefile.cpp"), QStringLiteral("instance->setBar(0);\n setFoo(0); /*not replaced*/"))); QTest::newRow("Template with captures") << (FileList() << File(QStringLiteral("somefile.cpp"), QStringLiteral("inst::func(1, 2)\n otherInst :: func (\"foo\")\n func()"))) << "func" << "([a-z0-9_$]+)\\s*::\\s*\\b%s\\b\\s*\\(" << "REPL" << "\\1::%s(" << (FileList() << File(QStringLiteral("somefile.cpp"), QStringLiteral("inst::REPL(1, 2)\n otherInst::REPL(\"foo\")\n func()"))); QTest::newRow("Regexp pattern") << (FileList() << File(QStringLiteral("somefile.txt"), QStringLiteral("foobar\n foooobar\n fake"))) << "f\\w*o" << "%s" << "FOO" << "%s" << (FileList() << File(QStringLiteral("somefile.txt"), QStringLiteral("FOObar\n FOObar\n fake"))); } void FindReplaceTest::testReplace() { QFETCH(FileList, subject); QFETCH(QString, searchPattern); QFETCH(QString, searchTemplate); QFETCH(QString, replace); QFETCH(QString, replaceTemplate); QFETCH(FileList, result); QTemporaryDir tempDir; QDir dir(tempDir.path()); // we need some convenience functions that are not in QTemporaryDir - foreach(const File& fileData, subject) - { + for (const File& fileData : qAsConst(subject)) { QFile file(dir.filePath(fileData.first)); QVERIFY(file.open(QIODevice::WriteOnly)); QVERIFY(file.write(fileData.second.toUtf8()) != -1); file.close(); } auto *job = new GrepJob(this); auto *model = new GrepOutputModel(job); GrepJobSettings settings; job->setOutputModel(model); job->setDirectoryChoice(QList() << QUrl::fromLocalFile(dir.path())); settings.projectFilesOnly = false; settings.caseSensitive = true; settings.regexp = true; settings.depth = -1; // fully recursive settings.pattern = searchPattern; settings.searchTemplate = searchTemplate; settings.replacementTemplate = replaceTemplate; settings.files = QStringLiteral("*"); settings.exclude = QString(); job->setSettings(settings); QVERIFY(job->exec()); QVERIFY(model->hasResults()); model->setReplacement(replace); model->makeItemsCheckable(true); model->doReplacements(); - foreach(const File& fileData, result) - { + for (const File& fileData : qAsConst(result)) { QFile file(dir.filePath(fileData.first)); QVERIFY(file.open(QIODevice::ReadOnly)); QCOMPARE(QString(file.readAll()), fileData.second); file.close(); } tempDir.remove(); } QTEST_MAIN(FindReplaceTest)