plugin_search.cpp 68.1 KB
Newer Older
Kåre Särs's avatar
Kåre Särs committed
1
/*   Kate search plugin
2
 *
3
 * Copyright (C) 2011-2013 by Kåre Särs <kare.sars@iki.fi>
Kåre Särs's avatar
Kåre Särs committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * 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.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program in a file called COPYING; if not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 */

#include "plugin_search.h"

23 24
#include "htmldelegate.h"

25
#include <ktexteditor/application.h>
26
#include <ktexteditor/editor.h>
Kåre Särs's avatar
Kåre Särs committed
27 28
#include <ktexteditor/view.h>
#include <ktexteditor/document.h>
29 30 31
#include <ktexteditor/markinterface.h>
#include <ktexteditor/movinginterface.h>
#include <ktexteditor/movingrange.h>
32
#include <ktexteditor/configinterface.h>
Kåre Särs's avatar
Kåre Särs committed
33

34
#include "kacceleratormanager.h"
Kåre Särs's avatar
Kåre Särs committed
35
#include <kactioncollection.h>
36
#include <klocalizedstring.h>
Kåre Särs's avatar
Kåre Särs committed
37 38 39
#include <kpluginfactory.h>
#include <kpluginloader.h>
#include <kaboutdata.h>
40
#include <kurlcompletion.h>
41
#include <klineedit.h>
42
#include <kcolorscheme.h>
43 44 45 46
#include <kiconloader.h>

#include <KXMLGUIFactory>
#include <KConfigGroup>
47

48 49
#include <QKeyEvent>
#include <QClipboard>
50
#include <QMenu>
51
#include <QMetaObject>
52
#include <QTextDocument>
53
#include <QScrollBar>
54 55
#include <QFileInfo>
#include <QDir>
56 57
#include <QComboBox>
#include <QCompleter>
58 59 60 61 62 63 64 65 66

static QUrl localFileDirUp (const QUrl &url)
{
    if (!url.isLocalFile())
        return url;
    
    // else go up
    return QUrl::fromLocalFile (QFileInfo (url.toLocalFile()).dir().absolutePath());
}
67 68 69 70 71 72 73 74 75 76 77 78

static QAction *menuEntry(QMenu *menu,
                          const QString &before, const QString &after, const QString &desc,
                          QString menuBefore = QString(), QString menuAfter = QString());

static QAction *menuEntry(QMenu *menu,
                          const QString &before, const QString &after, const QString &desc,
                          QString menuBefore, QString menuAfter)
{
    if (menuBefore.isEmpty()) menuBefore = before;
    if (menuAfter.isEmpty())  menuAfter = after;

79
    QAction *const action = menu->addAction(menuBefore + menuAfter + QLatin1Char('\t') + desc);
80 81
    if (!action) return 0;

82
    action->setData(QString(before + QLatin1Char(' ') + after));
83 84
    return action;
}
Kåre Särs's avatar
Kåre Särs committed
85

86 87 88 89 90 91 92
class TreeWidgetItem : public QTreeWidgetItem {
public:
    TreeWidgetItem(QTreeWidget* parent):QTreeWidgetItem(parent){}
    TreeWidgetItem(QTreeWidget* parent, const QStringList &list):QTreeWidgetItem(parent, list){}
    TreeWidgetItem(QTreeWidgetItem* parent, const QStringList &list):QTreeWidgetItem(parent, list){}
private:
    bool operator<(const QTreeWidgetItem &other)const {
93
        if (childCount() == 0) {
94 95 96 97
            int line = data(0, ReplaceMatches::LineRole).toInt();
            int column = data(0, ReplaceMatches::ColumnRole).toInt();
            int oLine = other.data(0, ReplaceMatches::LineRole).toInt();
            int oColumn = other.data(0, ReplaceMatches::ColumnRole).toInt();
98 99 100 101 102 103 104 105
            if (line < oLine) {
                return true;
            }
            if ((line == oLine) && (column < oColumn)) {
                return true;
            }
            return false;
        }
106 107
        int sepCount = data(0, ReplaceMatches::FileUrlRole).toString().count(QDir::separator());
        int oSepCount = other.data(0, ReplaceMatches::FileUrlRole).toString().count(QDir::separator());
108 109
        if (sepCount < oSepCount) return true;
        if (sepCount > oSepCount) return false;
110
        return data(0, ReplaceMatches::FileUrlRole).toString().toLower() < other.data(0, ReplaceMatches::FileUrlRole).toString().toLower();
111 112 113
    }
};

114 115 116
Results::Results(QWidget *parent): QWidget(parent), matches(0)
{
    setupUi(this);
117

118 119 120 121
    tree->setItemDelegate(new SPHtmlDelegate(tree));
}


122
K_PLUGIN_FACTORY_WITH_JSON (KatePluginSearchFactory, "katesearch.json", registerPlugin<KatePluginSearch>();)
Kåre Särs's avatar
Kåre Särs committed
123 124

KatePluginSearch::KatePluginSearch(QObject* parent, const QList<QVariant>&)
125
    : KTextEditor::Plugin (parent),
126
    m_searchCommand(0)
Kåre Särs's avatar
Kåre Särs committed
127
{
128 129
    // FIXME KF5
    //KGlobal::locale()->insertCatalog("katesearch");
130

131
    m_searchCommand = new KateSearchCommand(this);
Kåre Särs's avatar
Kåre Särs committed
132 133 134 135
}

KatePluginSearch::~KatePluginSearch()
{
136
    delete m_searchCommand;
Kåre Särs's avatar
Kåre Särs committed
137 138
}

139
QObject *KatePluginSearch::createView(KTextEditor::MainWindow *mainWindow)
Kåre Särs's avatar
Kåre Särs committed
140
{
141
    KatePluginSearchView *view = new KatePluginSearchView(this, mainWindow, KTextEditor::Editor::instance()->application());
142 143 144 145
    connect(m_searchCommand, SIGNAL(setSearchPlace(int)), view, SLOT(setSearchPlace(int)));
    connect(m_searchCommand, SIGNAL(setCurrentFolder()), view, SLOT(setCurrentFolder()));
    connect(m_searchCommand, SIGNAL(setSearchString(QString)), view, SLOT(setSearchString(QString)));
    connect(m_searchCommand, SIGNAL(startSearch()), view, SLOT(startSearch()));
146
    connect(m_searchCommand, SIGNAL(newTab()), view, SLOT(addTab()));
147

148
    return view;
Kåre Särs's avatar
Kåre Särs committed
149 150 151
}


152
bool ContainerWidget::focusNextPrevChild (bool next)
153
{
154 155 156
    QWidget* fw = focusWidget();
    bool found = false;
    emit nextFocus(fw, &found, next);
157

158 159 160 161
    if (found) {
        return true;
    }
    return QWidget::focusNextPrevChild(next);
162 163
}

164
void KatePluginSearchView::nextFocus(QWidget *currentWidget, bool *found, bool next)
165
{
166 167 168 169 170 171
    *found = false;

    if (!currentWidget) {
        return;
    }

172
    // we use the object names here because there can be multiple replaceButtons (on multiple result tabs)
173
    if (next) {
Joseph Wenninger's avatar
Joseph Wenninger committed
174
        if (currentWidget->objectName() == QStringLiteral("tree")) {
175 176 177 178
            m_ui.newTabButton->setFocus();
            *found = true;
            return;
        }
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
        if (currentWidget == m_ui.displayOptions) {
            if (m_ui.displayOptions->isChecked()) {
                m_ui.newTabButton->setFocus();
                *found = true;
                return;
            }
            else {
                Results *res = qobject_cast<Results *>(m_ui.resultTabWidget->currentWidget());
                if (!res) {
                    return;
                }
                res->tree->setFocus();
                *found = true;
                return;
            }
194
        }
195
    }
196 197
    else {
        if (currentWidget == m_ui.newTabButton) {
198
            if (m_ui.displayOptions->isChecked()) {
199 200 201 202 203 204 205 206 207 208 209
                m_ui.displayOptions->setFocus();
            }
            else {
                Results *res = qobject_cast<Results *>(m_ui.resultTabWidget->currentWidget());
                if (!res) {
                    return;
                }
                res->tree->setFocus();
            }
            *found = true;
            return;
210 211
        }
        else {
Joseph Wenninger's avatar
Joseph Wenninger committed
212
            if (currentWidget->objectName() == QStringLiteral("tree")) {
213 214
                m_ui.displayOptions->setFocus();
                *found = true;
215 216 217
                return;
            }
        }
218 219 220
    }
}

221
KatePluginSearchView::KatePluginSearchView(KTextEditor::Plugin *plugin, KTextEditor::MainWindow *mainWin, KTextEditor::Application* application)
222
: QObject (mainWin),
223
m_kateApp(application),
224
m_curResults(0),
225
m_searchJustOpened(false),
226
m_switchToProjectModeWhenAvailable(false),
227 228
m_searchDiskFilesDone(true),
m_searchOpenFilesDone(true),
229 230
m_projectPluginView(0),
m_mainWindow (mainWin)
Kåre Särs's avatar
Kåre Särs committed
231
{
Joseph Wenninger's avatar
Joseph Wenninger committed
232 233
    KXMLGUIClient::setComponentName (QStringLiteral("katesearch"), i18n ("Kate Search & Replace"));
    setXMLFile( QStringLiteral("ui.rc") );
234
  
Joseph Wenninger's avatar
Joseph Wenninger committed
235
    m_toolView = mainWin->createToolView (plugin, QStringLiteral("kate_plugin_katesearch"),
236
                                          KTextEditor::MainWindow::Bottom,
Joseph Wenninger's avatar
Joseph Wenninger committed
237
                                          SmallIcon(QStringLiteral("edit-find")),
238 239
                                          i18n("Search and Replace"));

240
    ContainerWidget *container = new ContainerWidget(m_toolView);
241
    m_ui.setupUi(container);
Kåre Särs's avatar
Kåre Särs committed
242
    container->setFocusProxy(m_ui.searchCombo);
243
    connect(container, SIGNAL(nextFocus(QWidget*,bool*,bool)), this, SLOT(nextFocus(QWidget*,bool*,bool)));
244

Joseph Wenninger's avatar
Joseph Wenninger committed
245
    QAction *a = actionCollection()->addAction(QStringLiteral("search_in_files"));
Kåre Särs's avatar
Kåre Särs committed
246
    a->setText(i18n("Search in Files"));
247
    connect(a, SIGNAL(triggered(bool)), this, SLOT(openSearchView()));
248

Joseph Wenninger's avatar
Joseph Wenninger committed
249
    a = actionCollection()->addAction(QStringLiteral("search_in_files_new_tab"));
250 251
    a->setText(i18n("Search in Files (in new tab)"));
    // first add tab, then open search view, since open search view switches to show the search options
252
    connect(a, SIGNAL(triggered(bool)), this, SLOT(addTab()));
253
    connect(a, SIGNAL(triggered(bool)), this, SLOT(openSearchView()));
254

Joseph Wenninger's avatar
Joseph Wenninger committed
255
    a = actionCollection()->addAction(QStringLiteral("go_to_next_match"));
256 257 258
    a->setText(i18n("Go to Next Match"));
    connect(a, SIGNAL(triggered(bool)), this, SLOT(goToNextMatch()));

Joseph Wenninger's avatar
Joseph Wenninger committed
259
    a = actionCollection()->addAction(QStringLiteral("go_to_prev_match"));
260 261 262
    a->setText(i18n("Go to Previous Match"));
    connect(a, SIGNAL(triggered(bool)), this, SLOT(goToPreviousMatch()));

263
    m_ui.resultTabWidget->tabBar()->setSelectionBehaviorOnRemove(QTabBar::SelectLeftTab);
264
    KAcceleratorManager::setNoAccel(m_ui.resultTabWidget);
265

Joseph Wenninger's avatar
Joseph Wenninger committed
266 267 268 269 270 271 272 273
    m_ui.displayOptions->setIcon(SmallIcon(QStringLiteral("arrow-down-double")));
    m_ui.searchButton->setIcon(SmallIcon(QStringLiteral("edit-find")));
    m_ui.stopButton->setIcon(SmallIcon(QStringLiteral("process-stop")));
    m_ui.searchPlaceCombo->setItemIcon(0, SmallIcon(QStringLiteral("text-plain")));
    m_ui.searchPlaceCombo->setItemIcon(1, SmallIcon(QStringLiteral("folder")));
    m_ui.folderUpButton->setIcon(SmallIcon(QStringLiteral("go-up")));
    m_ui.currentFolderButton->setIcon(SmallIcon(QStringLiteral("view-refresh")));
    m_ui.newTabButton->setIcon(SmallIcon(QStringLiteral("tab-new")));
274

275 276
    m_ui.filterCombo->setToolTip(i18n("Comma separated list of file types to search in. Example: \"*.cpp,*.h\"\n"));
    m_ui.excludeCombo->setToolTip(i18n("Comma separated list of files and directories to exclude from the search. Example: \"build*\""));
277

278 279
    // the order here is important to get the tabBar hidden for only one tab
    addTab();
280
    m_ui.resultTabWidget->tabBar()->hide();
281 282 283 284 285 286 287 288 289 290

    // get url-requester's combo box and sanely initialize
    KComboBox* cmbUrl = m_ui.folderRequester->comboBox();
    cmbUrl->setDuplicatesEnabled(false);
    cmbUrl->setEditable(true);
    m_ui.folderRequester->setMode(KFile::Directory | KFile::LocalOnly);
    KUrlCompletion* cmpl = new KUrlCompletion(KUrlCompletion::DirCompletion);
    cmbUrl->setCompletionObject(cmpl);
    cmbUrl->setAutoDeleteCompletionObject(true);

291
    connect(m_ui.newTabButton,     SIGNAL(clicked()), this, SLOT(addTab()));
Christoph Cullmann's avatar
Christoph Cullmann committed
292
    connect(m_ui.resultTabWidget,  SIGNAL(tabCloseRequested(int)), this, SLOT(tabCloseRequested(int)));
293
    connect(m_ui.resultTabWidget,  SIGNAL(currentChanged(int)), this, SLOT(resultTabChanged(int)));
294

295
    connect(m_ui.folderUpButton,   SIGNAL(clicked()), this, SLOT(navigateFolderUp()));
296 297
    connect(m_ui.currentFolderButton, SIGNAL(clicked()), this, SLOT(setCurrentFolder()));

298 299 300 301
    connect(m_ui.searchCombo,      SIGNAL(editTextChanged(QString)), &m_changeTimer, SLOT(start()));
    connect(m_ui.matchCase,        SIGNAL(stateChanged(int)), &m_changeTimer, SLOT(start()));
    connect(m_ui.useRegExp,        SIGNAL(stateChanged(int)), &m_changeTimer, SLOT(start()));
    m_changeTimer.setInterval(300);
Kåre Särs's avatar
Kåre Särs committed
302
    m_changeTimer.setSingleShot(true);
303 304
    connect(&m_changeTimer, SIGNAL(timeout()), this, SLOT(startSearchWhileTyping()));

305
    connect(m_ui.searchCombo->lineEdit(), SIGNAL(returnPressed()), this, SLOT(startSearch()));
306 307 308 309 310 311 312
    connect(m_ui.folderRequester,  SIGNAL(returnPressed()), this, SLOT(startSearch()));
    connect(m_ui.filterCombo,      SIGNAL(returnPressed()), this, SLOT(startSearch()));
    connect(m_ui.excludeCombo,     SIGNAL(returnPressed()), this, SLOT(startSearch()));
    connect(m_ui.searchButton,     SIGNAL(clicked()),       this, SLOT(startSearch()));

    connect(m_ui.displayOptions,   SIGNAL(toggled(bool)), this, SLOT(toggleOptions(bool)));
    connect(m_ui.searchPlaceCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(searchPlaceChanged()));
313

314
    connect(m_ui.stopButton,       SIGNAL(clicked()), &m_searchOpenFiles, SLOT(cancelSearch()));
315 316
    connect(m_ui.stopButton,       SIGNAL(clicked()), &m_searchDiskFiles, SLOT(cancelSearch()));
    connect(m_ui.stopButton,       SIGNAL(clicked()), &m_folderFilesList, SLOT(cancelSearch()));
317
    connect(m_ui.stopButton,       SIGNAL(clicked()), &m_replacer,        SLOT(cancelReplace()));
318

319 320 321 322
    connect(m_ui.nextButton,       SIGNAL(clicked()), this, SLOT(goToNextMatch()));

    connect(m_ui.replaceButton,     SIGNAL(clicked(bool)),   this, SLOT(replaceSingleMatch()));
    connect(m_ui.replaceCheckedBtn, SIGNAL(clicked(bool)),   this, SLOT(replaceChecked()));
323
    connect(m_ui.replaceCombo->lineEdit(), SIGNAL(returnPressed()), this, SLOT(replaceChecked()));
324 325 326



Kåre Särs's avatar
Kåre Särs committed
327 328
    m_ui.displayOptions->setChecked(true);

329 330
    connect(&m_searchOpenFiles, SIGNAL(matchFound(QString,QString,int,int,QString,int)),
            this,                 SLOT(matchFound(QString,QString,int,int,QString,int)));
Kåre Särs's avatar
Kåre Särs committed
331
    connect(&m_searchOpenFiles, SIGNAL(searchDone()),  this, SLOT(searchDone()));
332
    connect(&m_searchOpenFiles, SIGNAL(searching(QString)), this, SLOT(searching(QString)));
Kåre Särs's avatar
Kåre Särs committed
333

334
    connect(&m_folderFilesList, SIGNAL(finished()),  this, SLOT(folderFileListChanged()));
335

336 337
    connect(&m_searchDiskFiles, SIGNAL(matchFound(QString,QString,int,int,QString,int)),
            this,                 SLOT(matchFound(QString,QString,int,int,QString,int)));
338
    connect(&m_searchDiskFiles, SIGNAL(searchDone()),  this, SLOT(searchDone()));
339
    connect(&m_searchDiskFiles, SIGNAL(searching(QString)), this, SLOT(searching(QString)));
340

341
    connect(m_kateApp, SIGNAL(documentWillBeDeleted(KTextEditor::Document*)),
342
            &m_searchOpenFiles, SLOT(cancelSearch()));
343

344
    connect(m_kateApp, SIGNAL(documentWillBeDeleted(KTextEditor::Document*)),
345 346
            &m_replacer, SLOT(cancelReplace()));

347
    connect(m_kateApp, SIGNAL(documentWillBeDeleted(KTextEditor::Document*)),
348 349
            this, SLOT(clearDocMarks(KTextEditor::Document*)));

350 351 352
    connect(&m_replacer, SIGNAL(matchReplaced(KTextEditor::Document*,int,int,int)),
            this, SLOT(addMatchMark(KTextEditor::Document*,int,int,int)));

353 354 355 356
    // Hook into line edit context menus
    m_ui.searchCombo->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(m_ui.searchCombo, SIGNAL(customContextMenuRequested(QPoint)), this,
            SLOT(searchContextMenu(QPoint)));
357 358 359 360 361 362 363 364 365
    m_ui.searchCombo->completer()->setCompletionMode(QCompleter::PopupCompletion);
    m_ui.searchCombo->setInsertPolicy(QComboBox::NoInsert);
    m_ui.searchCombo->lineEdit()->setClearButtonEnabled(true);
    m_ui.searchCombo->setMaxCount(25);

    m_ui.replaceCombo->completer()->setCompletionMode(QCompleter::PopupCompletion);
    m_ui.replaceCombo->setInsertPolicy(QComboBox::NoInsert);
    m_ui.replaceCombo->lineEdit()->setClearButtonEnabled(true);
    m_ui.replaceCombo->setMaxCount(25);
366

367
    connect(m_mainWindow, SIGNAL(unhandledShortcutOverride(QEvent*)),
368 369
            this, SLOT(handleEsc(QEvent*)));

370
    // watch for project plugin view creation/deletion
Christoph Cullmann's avatar
Christoph Cullmann committed
371 372
    connect(m_mainWindow, SIGNAL(pluginViewCreated (const QString &, QObject *))
        , this, SLOT(slotPluginViewCreated (const QString &, QObject *)));
373

Christoph Cullmann's avatar
Christoph Cullmann committed
374 375
    connect(m_mainWindow, SIGNAL(pluginViewDeleted (const QString &, QObject *))
        , this, SLOT(slotPluginViewDeleted (const QString &, QObject *)));
376

Christoph Cullmann's avatar
Christoph Cullmann committed
377
    connect(m_mainWindow, SIGNAL(viewChanged(KTextEditor::View *)), this, SLOT(docViewChanged()));
378 379


380
    // update once project plugin state manually
Joseph Wenninger's avatar
Joseph Wenninger committed
381
    m_projectPluginView = m_mainWindow->pluginView (QStringLiteral("kateprojectplugin"));
382 383
    slotProjectFileNameChanged ();

384
    m_replacer.setDocumentManager(m_kateApp);
385
    connect(&m_replacer, SIGNAL(replaceDone()), this, SLOT(replaceDone()));
386

387 388
    searchPlaceChanged();

389 390
    m_toolView->installEventFilter(this);

391
    m_mainWindow->guiFactory()->addClient(this);
Kåre Särs's avatar
Kåre Särs committed
392 393 394 395
}

KatePluginSearchView::~KatePluginSearchView()
{
396 397
    clearMarks();

398
    m_mainWindow->guiFactory()->removeClient(this);
399
    delete m_toolView;
Kåre Särs's avatar
Kåre Särs committed
400 401
}

402
void KatePluginSearchView::navigateFolderUp()
403 404
{
    // navigate one folder up
405
    m_ui.folderRequester->setUrl(localFileDirUp (m_ui.folderRequester->url()));
406 407
}

408 409
void KatePluginSearchView::setCurrentFolder()
{
410
    if (!m_mainWindow) {
411 412
        return;
    }
413
    KTextEditor::View* editView = m_mainWindow->activeView();
414 415
    if (editView && editView->document()) {
        // upUrl as we want the folder not the file
416
        m_ui.folderRequester->setUrl(localFileDirUp (editView->document()->url()));
417 418 419
    }
}

420 421 422 423 424 425 426 427 428 429 430 431

QString KatePluginSearchView::currentWord(const KTextEditor::Document& document, const KTextEditor::Cursor& cursor ) const
{
    QString textLine = document.line(cursor.line());

    int len = textLine.length();

    if (cursor.column() > len) {       // Probably because of non-wrapping cursor mode.
        return QString();
    }

    int start = cursor.column();
432
    for(int currPos = cursor.column()-1; currPos >= 0; currPos--) {
433
        if (textLine.at(currPos).isLetterOrNumber() || (textLine[currPos]==QLatin1Char('_')) || (textLine[currPos]==QLatin1Char('~'))) {
434 435 436 437 438 439 440 441 442
            start = currPos;
        }
        else {
            break;
        }
    }

    int end = cursor.column();
    while (end < len && (textLine.at(end).isLetterOrNumber()
443
                     || (textLine[end]==QLatin1Char('_')) || (textLine[end]==QLatin1Char('~')))) {
444 445 446 447 448 449
        end++;
    }

    return textLine.mid(start, (end - start));
}

450
void KatePluginSearchView::openSearchView()
Kåre Särs's avatar
Kåre Särs committed
451
{
452
    if (!m_mainWindow) {
Kåre Särs's avatar
Kåre Särs committed
453 454 455
        return;
    }
    if (!m_toolView->isVisible()) {
456
        m_mainWindow->showToolView(m_toolView);
457
    }
458
    m_ui.searchCombo->setFocus(Qt::OtherFocusReason);
459
    m_ui.displayOptions->setChecked(true);
460

461
    KTextEditor::View* editView = m_mainWindow->activeView();
462
    if (editView && editView->document()) {
463
        if (m_ui.folderRequester->text().isEmpty()) {
464
            // upUrl as we want the folder not the file
465
            m_ui.folderRequester->setUrl(localFileDirUp (editView->document()->url()));
466
        }
467
        QString selection;
468
        if (editView->selection()) {
469
            selection = editView->selectionText();
470
            // remove possible trailing '\n'
471
            if (selection.endsWith(QLatin1Char('\n'))) {
472 473
                selection = selection.left(selection.size() -1);
            }
474
        }
475 476 477 478
        if (selection.isEmpty()) {
            selection = currentWord(*editView->document(), editView->cursorPosition());
        }

479
        if (!selection.isEmpty() && !selection.contains(QLatin1Char('\n'))) {
480 481 482 483 484
            m_ui.searchCombo->blockSignals(true);
            m_ui.searchCombo->lineEdit()->setText(selection);
            m_ui.searchCombo->blockSignals(false);
        }

485 486
        m_ui.searchCombo->lineEdit()->selectAll();
        m_searchJustOpened = true;
487
        startSearchWhileTyping();
Kåre Särs's avatar
Kåre Särs committed
488 489 490
    }
}

491 492
void KatePluginSearchView::handleEsc(QEvent *e)
{
493
    if (!m_mainWindow) return;
494 495 496 497 498

    QKeyEvent *k = static_cast<QKeyEvent *>(e);
    if (k->key() == Qt::Key_Escape && k->modifiers() == Qt::NoModifier) {

        if (m_toolView->isVisible()) {
499
            m_mainWindow->hideToolView(m_toolView);
500 501 502 503 504 505 506
        }
        else {
            clearMarks();
        }
    }
}

507 508 509 510 511
void KatePluginSearchView::setSearchString(const QString &pattern)
{
    m_ui.searchCombo->lineEdit()->setText(pattern);
}

512 513 514 515 516 517 518 519 520
void KatePluginSearchView::toggleOptions(bool show)
{
    m_ui.stackedWidget->setCurrentIndex((show) ? 1:0);
}

void KatePluginSearchView::setSearchPlace(int place)
{
    m_ui.searchPlaceCombo->setCurrentIndex(place);
}
521 522 523 524

QStringList KatePluginSearchView::filterFiles(const QStringList& files) const
{
    QString types = m_ui.filterCombo->currentText();
525
    QString excludes = m_ui.excludeCombo->currentText();
Joseph Wenninger's avatar
Joseph Wenninger committed
526
    if (((types.isEmpty() || types == QStringLiteral("*"))) && (excludes.isEmpty())) {
527 528 529 530
        // shortcut for use all files
        return files;
    }

531
    QStringList tmpTypes = types.split(QLatin1Char(','));
532 533 534 535 536 537 538
    QVector<QRegExp> typeList;
    for (int i=0; i<tmpTypes.size(); i++) {
        QRegExp rx(tmpTypes[i]);
        rx.setPatternSyntax(QRegExp::Wildcard);
        typeList << rx;
    }

539
    QStringList tmpExcludes = excludes.split(QLatin1Char(','));
540 541 542 543 544 545 546
    QVector<QRegExp> excludeList;
    for (int i=0; i<tmpExcludes.size(); i++) {
        QRegExp rx(tmpExcludes[i]);
        rx.setPatternSyntax(QRegExp::Wildcard);
        excludeList << rx;
    }

547 548 549
    QStringList filteredFiles;
    foreach (QString fileName, files) {
        bool isInSubDir = fileName.startsWith(m_resultBaseDir);
550
        QString nameToCheck = fileName;
551
        if (isInSubDir) {
552
            nameToCheck = fileName.mid(m_resultBaseDir.size());
553 554
        }

555 556 557 558 559 560 561 562 563 564 565 566
        bool skip = false;
        for (int i=0; i<excludeList.size(); i++) {
            if (excludeList[i].exactMatch(nameToCheck)) {
                skip = true;
                break;
            }
        }
        if (skip) {
            continue;
        }


567
        for (int i=0; i<typeList.size(); i++) {
568
            if (typeList[i].exactMatch(nameToCheck)) {
569 570 571 572 573 574 575 576
                filteredFiles << fileName;
                break;
            }
        }
    }
    return filteredFiles;
}

577
void KatePluginSearchView::folderFileListChanged()
Kåre Särs's avatar
Kåre Särs committed
578
{
579 580
    m_searchDiskFilesDone = false;
    m_searchOpenFilesDone = false;
581

582
    if (!m_curResults) {
583
        qWarning() << "This is a bug";
584 585 586
        m_searchDiskFilesDone = true;
        m_searchOpenFilesDone = true;
        searchDone();
587 588
        return;
    }
589
    QStringList fileList = m_folderFilesList.fileList();
590

591
    QList<KTextEditor::Document*> openList;
592 593
    for (int i=0; i<m_kateApp->documents().size(); i++) {
        int index = fileList.indexOf(m_kateApp->documents()[i]->url().toString());
594
        if (index != -1) {
595
            openList << m_kateApp->documents()[i];
596 597
            fileList.removeAt(index);
        }
Kåre Särs's avatar
Kåre Särs committed
598
    }
599 600 601 602 603 604

    // search order is important: Open files starts immediately and should finish
    // earliest after first event loop.
    // The DiskFile might finish immediately
    if (openList.size() > 0) {
        m_searchOpenFiles.startSearch(openList, m_curResults->regExp);
605 606
    }
    else {
607
        m_searchOpenFilesDone = true;
Kåre Särs's avatar
Kåre Särs committed
608 609
    }

610
    m_searchDiskFiles.startSearch(fileList, m_curResults->regExp);
Kåre Särs's avatar
Kåre Särs committed
611 612
}

613

Kåre Särs's avatar
Kåre Särs committed
614 615
void KatePluginSearchView::searchPlaceChanged()
{
616
    m_ui.displayOptions->setChecked(true);
617

618 619 620 621 622
    const bool inFolder = (m_ui.searchPlaceCombo->currentIndex() == 1);
    const bool inProject = (m_ui.searchPlaceCombo->currentIndex() == 2);

    m_ui.filterCombo->setEnabled(inFolder || inProject);

623
    m_ui.excludeCombo->setEnabled(inFolder || inProject);
624 625 626 627 628 629 630 631 632 633 634 635
    m_ui.folderRequester->setEnabled(inFolder);
    m_ui.folderUpButton->setEnabled(inFolder);
    m_ui.currentFolderButton->setEnabled(inFolder);
    m_ui.recursiveCheckBox->setEnabled(inFolder);
    m_ui.hiddenCheckBox->setEnabled(inFolder);
    m_ui.symLinkCheckBox->setEnabled(inFolder);
    m_ui.binaryCheckBox->setEnabled(inFolder);

    // ... and the labels:
    m_ui.folderLabel->setEnabled(m_ui.folderRequester->isEnabled());
    m_ui.filterLabel->setEnabled(m_ui.filterCombo->isEnabled());
    m_ui.excludeLabel->setEnabled(m_ui.excludeCombo->isEnabled());
Kåre Särs's avatar
Kåre Särs committed
636 637
}

638
void KatePluginSearchView::addHeaderItem()
639
{
640
    QTreeWidgetItem *item = new QTreeWidgetItem(m_curResults->tree, QStringList());
641 642
    item->setCheckState(0, Qt::Checked);
    item->setFlags(item->flags() | Qt::ItemIsTristate);
643
    m_curResults->tree->expandItem(item);
644 645
}

646
QTreeWidgetItem * KatePluginSearchView::rootFileItem(const QString &url, const QString &fName)
647
{
648
    if (!m_curResults) {
649 650 651
        return 0;
    }

652
    // FIXME KF5
653
    QUrl kurl = QUrl::fromUserInput(url);
654
    QString path = kurl.isLocalFile() ? localFileDirUp (kurl).path() : kurl.url();
655
    path.replace(m_resultBaseDir, QString());
656
    QString name = kurl.fileName();
657 658 659
    if (url.isEmpty()) {
        name = fName;
    }
660

661
    // make sure we have a root item
662
    if (m_curResults->tree->topLevelItemCount() == 0) {
663
        addHeaderItem();
664 665 666
    }
    QTreeWidgetItem *root = m_curResults->tree->topLevelItem(0);

667 668 669
    if (root->data(0, ReplaceMatches::FileNameRole).toString() == fName) {
        // The root item contains the document name ->
        // this is search as you type, return the root item
670 671 672
        return root;
    }

673
    for (int i=0; i<root->childCount(); i++) {
674
        //qDebug() << root->child(i)->data(0, ReplaceMatches::FileNameRole).toString() << fName;
675 676 677
        if ((root->child(i)->data(0, ReplaceMatches::FileUrlRole).toString() == url)&&
            (root->child(i)->data(0, ReplaceMatches::FileNameRole).toString() == fName)) {
            int matches = root->child(i)->data(0, ReplaceMatches::LineRole).toInt() + 1;
678
            QString tmpUrl = QString::fromLatin1("%1<b>%2</b>: <b>%3</b>").arg(path).arg(name).arg(matches);
679
            root->child(i)->setData(0, Qt::DisplayRole, tmpUrl);
680
            root->child(i)->setData(0, ReplaceMatches::LineRole, matches);
681
            return root->child(i);
682 683
        }
    }
684

685
    // file item not found create a new one
686
    QString tmpUrl = QString::fromLatin1("%1<b>%2</b>: <b>%3</b>").arg(path).arg(name).arg(1);
687

688
    TreeWidgetItem *item = new TreeWidgetItem(root, QStringList(tmpUrl));
689 690 691
    item->setData(0, ReplaceMatches::FileUrlRole, url);
    item->setData(0, ReplaceMatches::FileNameRole, fName);
    item->setData(0, ReplaceMatches::LineRole, 1);
692
    item->setCheckState(0, Qt::Checked);
693
    item->setFlags(item->flags() | Qt::ItemIsTristate);
694 695 696
    return item;
}

697 698 699 700 701
void KatePluginSearchView::addMatchMark(KTextEditor::Document* doc, int line, int column, int matchLen)
{
    if (!doc) return;

    KTextEditor::MovingInterface* miface = qobject_cast<KTextEditor::MovingInterface*>(doc);
702
    KTextEditor::ConfigInterface* ciface = qobject_cast<KTextEditor::ConfigInterface*>(m_mainWindow->activeView());
703
    KTextEditor::Attribute::Ptr attr(new KTextEditor::Attribute());
704 705 706

    bool replace = ((sender() == &m_replacer) || (sender() == 0) || (sender() == m_ui.replaceButton));
    if (replace) {
707
        QColor replaceColor(Qt::green);
Joseph Wenninger's avatar
Joseph Wenninger committed
708
        if (ciface) replaceColor = ciface->configValue(QStringLiteral("replace-highlight-color")).value<QColor>();
709
        attr->setBackground(replaceColor);
710 711
    }
    else {
712
        QColor searchColor(Qt::yellow);
Joseph Wenninger's avatar
Joseph Wenninger committed
713
        if (ciface) searchColor = ciface->configValue(QStringLiteral("search-highlight-color")).value<QColor>();
714
        attr->setBackground(searchColor);
715
    }
716 717 718 719 720 721 722 723
    // calculate end line in case of multi-line match
    int endLine = line;
    int endColumn = column+matchLen;
    while ((endLine < doc->lines()) &&  (endColumn > doc->line(endLine).size())) {
        endColumn -= doc->line(endLine).size();
        endColumn--; // remove one for '\n'
        endLine++;
    }
724

725
    KTextEditor::Range range(line, column, endLine, endColumn);
726

727
    if (m_curResults && !replace) {
728 729
        // special handling for "(?=\\n)" in multi-line search
        QRegExp tmpReg = m_curResults->regExp;
Joseph Wenninger's avatar
Joseph Wenninger committed
730
        if (m_curResults->regExp.pattern().endsWith(QStringLiteral("(?=\\n)"))) {
731
            QString newPatern = tmpReg.pattern();
Joseph Wenninger's avatar
Joseph Wenninger committed
732
            newPatern.replace(QStringLiteral("(?=\\n)"), QStringLiteral("$"));
733 734 735 736
            tmpReg.setPattern(newPatern);
        }

        if (tmpReg.indexIn(doc->text(range)) != 0) {
737
            qDebug() << doc->text(range) << "Does not match" << m_curResults->regExp.pattern();
738 739 740 741
            return;
        }
    }

742 743 744 745 746 747 748 749 750 751
    KTextEditor::MovingRange* mr = miface->newMovingRange(range);
    mr->setAttribute(attr);
    mr->setZDepth(-90000.0); // Set the z-depth to slightly worse than the selection
    mr->setAttributeOnlyForViews(true);
    m_matchRanges.append(mr);

    KTextEditor::MarkInterface* iface = qobject_cast<KTextEditor::MarkInterface*>(doc);
    if (!iface) return;
    iface->setMarkDescription(KTextEditor::MarkInterface::markType32, i18n("SearchHighLight"));
    iface->setMarkPixmap(KTextEditor::MarkInterface::markType32,
752
                         QIcon().pixmap(0,0));
753 754 755 756 757 758
    iface->addMark(line, KTextEditor::MarkInterface::markType32);

    connect(doc, SIGNAL(aboutToInvalidateMovingInterfaceContent(KTextEditor::Document*)),
            this, SLOT(clearMarks()), Qt::UniqueConnection);
}

759
void KatePluginSearchView::matchFound(const QString &url, const QString &fName, int line, int column,
760
                                      const QString &lineContent, int matchLen)
Kåre Särs's avatar
Kåre Särs committed
761
{
762
    if (!m_curResults) {
763 764
        return;
    }
765

766 767
    QString pre = lineContent.left(column).toHtmlEscaped();
    QString match = lineContent.mid(column, matchLen).toHtmlEscaped();
Joseph Wenninger's avatar
Joseph Wenninger committed
768
    match.replace(QLatin1Char('\n'), QStringLiteral("\\n"));
769
    QString post = lineContent.mid(column + matchLen).toHtmlEscaped();
Kåre Särs's avatar
Kåre Särs committed
770
    QStringList row;
Joseph Wenninger's avatar
Joseph Wenninger committed
771
    row << i18n("Line: <b>%1</b>: %2", line+1, pre+QStringLiteral("<b>")+match+QStringLiteral("</b>")+post);
772

773 774
    TreeWidgetItem *item = new TreeWidgetItem(rootFileItem(url, fName), row);
    item->setData(0, ReplaceMatches::FileUrlRole, url);
775
    item->setData(0, Qt::ToolTipRole, url);
776 777 778 779 780 781 782
    item->setData(0, ReplaceMatches::FileNameRole, fName);
    item->setData(0, ReplaceMatches::LineRole, line);
    item->setData(0, ReplaceMatches::ColumnRole, column);
    item->setData(0, ReplaceMatches::MatchLenRole, matchLen);
    item->setData(0, ReplaceMatches::PreMatchRole, pre);
    item->setData(0, ReplaceMatches::MatchRole, match);
    item->setData(0, ReplaceMatches::PostMatchRole, post);
783
    item->setCheckState (0, Qt::Checked);
784 785 786

    m_curResults->matches++;

787
    // Add mark if the document is open
788 789 790 791 792
    KTextEditor::Document* doc;
    if (url.isEmpty()) {
        doc = m_replacer.findNamed(fName);
    }
    else {
793
        doc = m_kateApp->findUrl(QUrl::fromUserInput(url));
794
    }
795
    addMatchMark(doc, line, column, matchLen);
796 797 798 799
}

void KatePluginSearchView::clearMarks()
{
800
    // FIXME: check for ongoing search...
801
    KTextEditor::MarkInterface* iface;
802
    foreach (KTextEditor::Document* doc, m_kateApp->documents()) {
803 804 805 806 807 808
        iface = qobject_cast<KTextEditor::MarkInterface*>(doc);
        if (iface) {
            const QHash<int, KTextEditor::Mark*> marks = iface->marks();
            QHashIterator<int, KTextEditor::Mark*> i(marks);
            while (i.hasNext()) {
                i.next();
809 810
                if (i.value()->type & KTextEditor::MarkInterface::markType32) {
                    iface->removeMark(i.value()->line, KTextEditor::MarkInterface::markType32);
811 812 813 814 815 816
                }
            }
        }
    }
    qDeleteAll(m_matchRanges);
    m_matchRanges.clear();
Kåre Särs's avatar
Kåre Särs committed
817 818
}

819 820
void KatePluginSearchView::clearDocMarks(KTextEditor::Document* doc)
{
821
    //qDebug() << sender();
822 823 824 825 826 827 828 829
    // FIXME: check for ongoing search...
    KTextEditor::MarkInterface* iface;
    iface = qobject_cast<KTextEditor::MarkInterface*>(doc);
    if (iface) {
        const QHash<int, KTextEditor::Mark*> marks = iface->marks();
        QHashIterator<int, KTextEditor::Mark*> i(marks);
        while (i.hasNext()) {
            i.next();
830 831
            if (i.value()->type & KTextEditor::MarkInterface::markType32) {
                iface->removeMark(i.value()->line, KTextEditor::MarkInterface::markType32);
832 833 834 835 836 837 838
            }
        }
    }

    int i = 0;
    while (i<m_matchRanges.size()) {
        if (m_matchRanges.at(i)->document() == doc) {
839
            //qDebug() << "removing mark in" << doc->url();
840 841 842 843 844 845 846 847 848
            delete m_matchRanges.at(i);
            m_matchRanges.removeAt(i);
        }
        else {
            i++;
        }
    }
}

849 850 851
void KatePluginSearchView::startSearch()
{
    m_changeTimer.stop(); // make sure not to start a "while you type" search now
852
    m_mainWindow->showToolView(m_toolView); // in case we are invoked from the command interface
853 854 855 856 857 858
    m_switchToProjectModeWhenAvailable = false; // now that we started, don't switch back automatically

    if (m_ui.searchCombo->currentText().isEmpty()) {
        // return pressed in the folder combo or filter combo
        return;
    }
859 860 861 862 863 864 865

    if (m_ui.searchCombo->findText(m_ui.searchCombo->currentText()) == -1) {
        m_ui.searchCombo->insertItem(1, m_ui.searchCombo->currentText());
        m_ui.searchCombo->setCurrentIndex(1);
    }

    if (m_ui.filterCombo->findText(m_ui.filterCombo->currentText()) == -1) {
866 867 868
        m_ui.filterCombo->insertItem(0, m_ui.filterCombo->currentText());
        m_ui.filterCombo->setCurrentIndex(0);
    }
869
    if (m_ui.excludeCombo->findText(m_ui.excludeCombo->currentText()) == -1) {
870 871