plugin_search.cpp 66.6 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 56 57 58 59 60 61 62 63 64
#include <QFileInfo>
#include <QDir>

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

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;

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

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

84 85 86 87 88 89 90
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 {
91
        if (childCount() == 0) {
92 93 94 95
            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();
96 97 98 99 100 101 102 103
            if (line < oLine) {
                return true;
            }
            if ((line == oLine) && (column < oColumn)) {
                return true;
            }
            return false;
        }
104 105
        int sepCount = data(0, ReplaceMatches::FileUrlRole).toString().count(QDir::separator());
        int oSepCount = other.data(0, ReplaceMatches::FileUrlRole).toString().count(QDir::separator());
106 107
        if (sepCount < oSepCount) return true;
        if (sepCount > oSepCount) return false;
108
        return data(0, ReplaceMatches::FileUrlRole).toString().toLower() < other.data(0, ReplaceMatches::FileUrlRole).toString().toLower();
109 110 111
    }
};

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

116 117 118 119
    tree->setItemDelegate(new SPHtmlDelegate(tree));
}


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

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

    KTextEditor::CommandInterface* iface =
130
    qobject_cast<KTextEditor::CommandInterface*>(KTextEditor::Editor::instance());
131 132 133 134
    if (iface) {
        m_searchCommand = new KateSearchCommand(this);
        iface->registerCommand(m_searchCommand);
    }
Kåre Särs's avatar
Kåre Särs committed
135 136 137 138
}

KatePluginSearch::~KatePluginSearch()
{
139
    KTextEditor::CommandInterface* iface =
140
    qobject_cast<KTextEditor::CommandInterface*>(KTextEditor::Editor::instance());
141 142 143
    if (iface && m_searchCommand) {
        iface->unregisterCommand(m_searchCommand);
    }
Kåre Särs's avatar
Kåre Särs committed
144 145
}

146
QObject *KatePluginSearch::createView(KTextEditor::MainWindow *mainWindow)
Kåre Särs's avatar
Kåre Särs committed
147
{
148
    KatePluginSearchView *view = new KatePluginSearchView(this, mainWindow, KTextEditor::Editor::instance()->application());
149 150 151 152
    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()));
153
    connect(m_searchCommand, SIGNAL(newTab()), view, SLOT(addTab()));
154

155
    return view;
Kåre Särs's avatar
Kåre Särs committed
156 157 158
}


159
bool ContainerWidget::focusNextPrevChild (bool next)
160
{
161 162 163
    QWidget* fw = focusWidget();
    bool found = false;
    emit nextFocus(fw, &found, next);
164

165 166 167 168
    if (found) {
        return true;
    }
    return QWidget::focusNextPrevChild(next);
169 170
}

171
void KatePluginSearchView::nextFocus(QWidget *currentWidget, bool *found, bool next)
172
{
173 174 175 176 177 178
    *found = false;

    if (!currentWidget) {
        return;
    }

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

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

247
    ContainerWidget *container = new ContainerWidget(m_toolView);
248
    m_ui.setupUi(container);
Kåre Särs's avatar
Kåre Särs committed
249
    container->setFocusProxy(m_ui.searchCombo);
250
    connect(container, SIGNAL(nextFocus(QWidget*,bool*,bool)), this, SLOT(nextFocus(QWidget*,bool*,bool)));
251

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

Joseph Wenninger's avatar
Joseph Wenninger committed
256
    a = actionCollection()->addAction(QStringLiteral("search_in_files_new_tab"));
257 258
    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
259
    connect(a, SIGNAL(triggered(bool)), this, SLOT(addTab()));
260
    connect(a, SIGNAL(triggered(bool)), this, SLOT(openSearchView()));
261

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

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

270
    m_ui.resultTabWidget->tabBar()->setSelectionBehaviorOnRemove(QTabBar::SelectLeftTab);
271
    KAcceleratorManager::setNoAccel(m_ui.resultTabWidget);
272

Joseph Wenninger's avatar
Joseph Wenninger committed
273 274 275 276 277 278 279 280
    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")));
281

282 283
    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*\""));
284

285 286
    // the order here is important to get the tabBar hidden for only one tab
    addTab();
287
    m_ui.resultTabWidget->tabBar()->hide();
288 289 290 291 292 293 294 295 296 297

    // 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);

298
    connect(m_ui.newTabButton,     SIGNAL(clicked()), this, SLOT(addTab()));
Christoph Cullmann's avatar
Christoph Cullmann committed
299
    connect(m_ui.resultTabWidget,  SIGNAL(tabCloseRequested(int)), this, SLOT(tabCloseRequested(int)));
300
    connect(m_ui.resultTabWidget,  SIGNAL(currentChanged(int)), this, SLOT(resultTabChanged(int)));
301

302
    connect(m_ui.folderUpButton,   SIGNAL(clicked()), this, SLOT(navigateFolderUp()));
303 304
    connect(m_ui.currentFolderButton, SIGNAL(clicked()), this, SLOT(setCurrentFolder()));

305 306 307 308
    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
309
    m_changeTimer.setSingleShot(true);
310 311 312 313 314 315 316 317 318 319
    connect(&m_changeTimer, SIGNAL(timeout()), this, SLOT(startSearchWhileTyping()));

    connect(m_ui.searchCombo,      SIGNAL(returnPressed()), this, SLOT(startSearch()));
    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()));
320

321
    connect(m_ui.stopButton,       SIGNAL(clicked()), &m_searchOpenFiles, SLOT(cancelSearch()));
322 323
    connect(m_ui.stopButton,       SIGNAL(clicked()), &m_searchDiskFiles, SLOT(cancelSearch()));
    connect(m_ui.stopButton,       SIGNAL(clicked()), &m_folderFilesList, SLOT(cancelSearch()));
324
    connect(m_ui.stopButton,       SIGNAL(clicked()), &m_replacer,        SLOT(cancelReplace()));
325

326 327 328 329 330 331 332 333
    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()));
    connect(m_ui.replaceCombo,      SIGNAL(returnPressed()), this, SLOT(replaceChecked()));



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

336 337
    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
338
    connect(&m_searchOpenFiles, SIGNAL(searchDone()),  this, SLOT(searchDone()));
339
    connect(&m_searchOpenFiles, SIGNAL(searching(QString)), this, SLOT(searching(QString)));
Kåre Särs's avatar
Kåre Särs committed
340

341
    connect(&m_folderFilesList, SIGNAL(finished()),  this, SLOT(folderFileListChanged()));
342

343 344
    connect(&m_searchDiskFiles, SIGNAL(matchFound(QString,QString,int,int,QString,int)),
            this,                 SLOT(matchFound(QString,QString,int,int,QString,int)));
345
    connect(&m_searchDiskFiles, SIGNAL(searchDone()),  this, SLOT(searchDone()));
346
    connect(&m_searchDiskFiles, SIGNAL(searching(QString)), this, SLOT(searching(QString)));
347

348
    connect(m_kateApp, SIGNAL(documentWillBeDeleted(KTextEditor::Document*)),
349
            &m_searchOpenFiles, SLOT(cancelSearch()));
350

351
    connect(m_kateApp, SIGNAL(documentWillBeDeleted(KTextEditor::Document*)),
352 353
            &m_replacer, SLOT(cancelReplace()));

354
    connect(m_kateApp, SIGNAL(documentWillBeDeleted(KTextEditor::Document*)),
355 356
            this, SLOT(clearDocMarks(KTextEditor::Document*)));

357 358 359
    connect(&m_replacer, SIGNAL(matchReplaced(KTextEditor::Document*,int,int,int)),
            this, SLOT(addMatchMark(KTextEditor::Document*,int,int,int)));

360 361 362 363 364
    // Hook into line edit context menus
    m_ui.searchCombo->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(m_ui.searchCombo, SIGNAL(customContextMenuRequested(QPoint)), this,
            SLOT(searchContextMenu(QPoint)));

365
    connect(m_mainWindow, SIGNAL(unhandledShortcutOverride(QEvent*)),
366 367
            this, SLOT(handleEsc(QEvent*)));

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

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

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


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

382
    m_replacer.setDocumentManager(m_kateApp);
383
    connect(&m_replacer, SIGNAL(replaceDone()), this, SLOT(replaceDone()));
384

385 386
    searchPlaceChanged();

387 388
    m_toolView->installEventFilter(this);

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

KatePluginSearchView::~KatePluginSearchView()
{
394 395
    clearMarks();

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

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

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

418 419 420 421 422 423 424 425 426 427 428 429

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

    // 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);
603 604
    }
    else {
605
        m_searchOpenFilesDone = true;
Kåre Särs's avatar
Kåre Särs committed
606 607
    }

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

611

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

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

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

621
    m_ui.excludeCombo->setEnabled(inFolder || inProject);
622 623 624 625 626 627 628 629 630 631 632 633
    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
634 635
}

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

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

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

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

665 666 667
    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
668 669 670
        return root;
    }

671
    for (int i=0; i<root->childCount(); i++) {
672
        //qDebug() << root->child(i)->data(0, ReplaceMatches::FileNameRole).toString() << fName;
673 674 675
        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;
676
            QString tmpUrl = QString::fromLatin1("%1<b>%2</b>: <b>%3</b>").arg(path).arg(name).arg(matches);
677
            root->child(i)->setData(0, Qt::DisplayRole, tmpUrl);
678
            root->child(i)->setData(0, ReplaceMatches::LineRole, matches);
679
            return root->child(i);
680 681
        }
    }
682

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

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

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

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

    bool replace = ((sender() == &m_replacer) || (sender() == 0) || (sender() == m_ui.replaceButton));
    if (replace) {
705
        QColor replaceColor(Qt::green);
Joseph Wenninger's avatar
Joseph Wenninger committed
706
        if (ciface) replaceColor = ciface->configValue(QStringLiteral("replace-highlight-color")).value<QColor>();
707
        attr->setBackground(replaceColor);
708 709
    }
    else {
710
        QColor searchColor(Qt::yellow);
Joseph Wenninger's avatar
Joseph Wenninger committed
711
        if (ciface) searchColor = ciface->configValue(QStringLiteral("search-highlight-color")).value<QColor>();
712
        attr->setBackground(searchColor);
713
    }
714 715 716 717 718 719 720 721
    // 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++;
    }
722

723
    KTextEditor::Range range(line, column, endLine, endColumn);
724

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

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

740 741 742 743 744 745 746 747 748 749
    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,
750
                         QIcon().pixmap(0,0));
751 752 753 754 755 756
    iface->addMark(line, KTextEditor::MarkInterface::markType32);

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

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

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

771 772
    TreeWidgetItem *item = new TreeWidgetItem(rootFileItem(url, fName), row);
    item->setData(0, ReplaceMatches::FileUrlRole, url);
773
    item->setData(0, Qt::ToolTipRole, url);
774 775 776 777 778 779 780
    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);
781
    item->setCheckState (0, Qt::Checked);
782 783 784

    m_curResults->matches++;

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

void KatePluginSearchView::clearMarks()
{
798
    // FIXME: check for ongoing search...
799
    KTextEditor::MarkInterface* iface;
800
    foreach (KTextEditor::Document* doc, m_kateApp->documents()) {
801 802 803 804 805 806
        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();
807 808
                if (i.value()->type & KTextEditor::MarkInterface::markType32) {
                    iface->removeMark(i.value()->line, KTextEditor::MarkInterface::markType32);
809 810 811 812 813 814
                }
            }
        }
    }
    qDeleteAll(m_matchRanges);
    m_matchRanges.clear();
Kåre Särs's avatar
Kåre Särs committed
815 816
}

817 818
void KatePluginSearchView::clearDocMarks(KTextEditor::Document* doc)
{
819
    //qDebug() << sender();
820 821 822 823 824 825 826 827
    // 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();
828 829
            if (i.value()->type & KTextEditor::MarkInterface::markType32) {
                iface->removeMark(i.value()->line, KTextEditor::MarkInterface::markType32);
830 831 832 833 834 835 836
            }
        }
    }

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

847 848 849
void KatePluginSearchView::startSearch()
{
    m_changeTimer.stop(); // make sure not to start a "while you type" search now
850
    m_mainWindow->showToolView(m_toolView); // in case we are invoked from the command interface
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
    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;
    }
    m_ui.searchCombo->addToHistory(m_ui.searchCombo->currentText());
    if(m_ui.filterCombo->findText(m_ui.filterCombo->currentText()) == -1) {
        m_ui.filterCombo->insertItem(0, m_ui.filterCombo->currentText());
        m_ui.filterCombo->setCurrentIndex(0);
    }
    if(m_ui.excludeCombo->findText(m_ui.excludeCombo->currentText()) == -1) {
        m_ui.excludeCombo->insertItem(0, m_ui.excludeCombo->currentText());
        m_ui.excludeCombo->setCurrentIndex(0);
    }
    m_curResults = qobject_cast<Results *>(m_ui.resultTabWidget->currentWidget());
    if (!m_curResults) {
868
        qWarning() << "This is a bug";
869 870 871 872 873 874 875 876 877 878 879
        return;
    }

    m_ui.newTabButton->setDisabled(true);
    m_ui.searchCombo->setDisabled(true);
    m_ui.searchButton->setDisabled(true);
    m_ui.displayOptions->setChecked (false);
    m_ui.displayOptions->setDisabled(true);
    m_ui.replaceCheckedBtn->setDisabled(true);
    m_ui.replaceButton->setDisabled(true);
    m_ui.nextAndStop->setCurrentIndex(1);
880
    m_ui.replaceCombo->setDisabled(true);
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901


    QRegExp reg(m_ui.searchCombo->currentText(),
                m_ui.matchCase->isChecked() ? Qt::CaseSensitive : Qt::CaseInsensitive,