plugin_search.cpp 69.8 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

#include <KXMLGUIFactory>
#include <KConfigGroup>
46

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

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

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;

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

81
    action->setData(QString(before + QLatin1Char(' ') + after));
82 83
    return action;
}
Kåre Särs's avatar
Kåre Särs committed
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:
91
    bool operator<(const QTreeWidgetItem &other) const Q_DECL_OVERRIDE {
92
        if (childCount() == 0) {
93 94 95 96
            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();
97 98 99 100 101 102 103 104
            if (line < oLine) {
                return true;
            }
            if ((line == oLine) && (column < oColumn)) {
                return true;
            }
            return false;
        }
105 106
        int sepCount = data(0, ReplaceMatches::FileUrlRole).toString().count(QDir::separator());
        int oSepCount = other.data(0, ReplaceMatches::FileUrlRole).toString().count(QDir::separator());
107 108
        if (sepCount < oSepCount) return true;
        if (sepCount > oSepCount) return false;
109
        return data(0, ReplaceMatches::FileUrlRole).toString().toLower() < other.data(0, ReplaceMatches::FileUrlRole).toString().toLower();
110 111 112
    }
};

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

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


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

KatePluginSearch::KatePluginSearch(QObject* parent, const QList<QVariant>&)
124
    : KTextEditor::Plugin (parent),
125
    m_searchCommand(0)
Kåre Särs's avatar
Kåre Särs committed
126
{
127
    m_searchCommand = new KateSearchCommand(this);
Kåre Särs's avatar
Kåre Särs committed
128 129 130 131
}

KatePluginSearch::~KatePluginSearch()
{
132
    delete m_searchCommand;
Kåre Särs's avatar
Kåre Särs committed
133 134
}

135
QObject *KatePluginSearch::createView(KTextEditor::MainWindow *mainWindow)
Kåre Särs's avatar
Kåre Särs committed
136
{
137
    KatePluginSearchView *view = new KatePluginSearchView(this, mainWindow, KTextEditor::Editor::instance()->application());
138 139 140 141
    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()));
142
    connect(m_searchCommand, SIGNAL(newTab()), view, SLOT(addTab()));
143

144
    return view;
Kåre Särs's avatar
Kåre Särs committed
145 146 147
}


148
bool ContainerWidget::focusNextPrevChild (bool next)
149
{
150 151 152
    QWidget* fw = focusWidget();
    bool found = false;
    emit nextFocus(fw, &found, next);
153

154 155 156 157
    if (found) {
        return true;
    }
    return QWidget::focusNextPrevChild(next);
158 159
}

160
void KatePluginSearchView::nextFocus(QWidget *currentWidget, bool *found, bool next)
161
{
162 163 164 165 166 167
    *found = false;

    if (!currentWidget) {
        return;
    }

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

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

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

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

Joseph Wenninger's avatar
Joseph Wenninger committed
245
    a = actionCollection()->addAction(QStringLiteral("search_in_files_new_tab"));
246 247
    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
248
    connect(a, SIGNAL(triggered(bool)), this, SLOT(addTab()));
249
    connect(a, SIGNAL(triggered(bool)), this, SLOT(openSearchView()));
250

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

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

259
    m_ui.resultTabWidget->tabBar()->setSelectionBehaviorOnRemove(QTabBar::SelectLeftTab);
260
    KAcceleratorManager::setNoAccel(m_ui.resultTabWidget);
261

262 263 264 265 266 267 268 269
    m_ui.displayOptions->setIcon(QIcon::fromTheme(QStringLiteral("arrow-down-double")));
    m_ui.searchButton->setIcon(QIcon::fromTheme(QStringLiteral("edit-find")));
    m_ui.stopButton->setIcon(QIcon::fromTheme(QStringLiteral("process-stop")));
    m_ui.searchPlaceCombo->setItemIcon(0, QIcon::fromTheme(QStringLiteral("text-plain")));
    m_ui.searchPlaceCombo->setItemIcon(1, QIcon::fromTheme(QStringLiteral("folder")));
    m_ui.folderUpButton->setIcon(QIcon::fromTheme(QStringLiteral("go-up")));
    m_ui.currentFolderButton->setIcon(QIcon::fromTheme(QStringLiteral("view-refresh")));
    m_ui.newTabButton->setIcon(QIcon::fromTheme(QStringLiteral("tab-new")));
270

271 272
    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*\""));
273

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

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

287
    connect(m_ui.newTabButton,     SIGNAL(clicked()), this, SLOT(addTab()));
Christoph Cullmann's avatar
Christoph Cullmann committed
288
    connect(m_ui.resultTabWidget,  SIGNAL(tabCloseRequested(int)), this, SLOT(tabCloseRequested(int)));
289
    connect(m_ui.resultTabWidget,  SIGNAL(currentChanged(int)), this, SLOT(resultTabChanged(int)));
290

291
    connect(m_ui.folderUpButton,   SIGNAL(clicked()), this, SLOT(navigateFolderUp()));
292 293
    connect(m_ui.currentFolderButton, SIGNAL(clicked()), this, SLOT(setCurrentFolder()));

294 295 296 297
    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
298
    m_changeTimer.setSingleShot(true);
299 300
    connect(&m_changeTimer, SIGNAL(timeout()), this, SLOT(startSearchWhileTyping()));

301
    connect(m_ui.searchCombo->lineEdit(), SIGNAL(returnPressed()), this, SLOT(startSearch()));
302 303 304 305 306 307 308
    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()));
309

310
    connect(m_ui.stopButton,       SIGNAL(clicked()), &m_searchOpenFiles, SLOT(cancelSearch()));
311 312
    connect(m_ui.stopButton,       SIGNAL(clicked()), &m_searchDiskFiles, SLOT(cancelSearch()));
    connect(m_ui.stopButton,       SIGNAL(clicked()), &m_folderFilesList, SLOT(cancelSearch()));
313
    connect(m_ui.stopButton,       SIGNAL(clicked()), &m_replacer,        SLOT(cancelReplace()));
314

315 316 317 318
    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()));
319
    connect(m_ui.replaceCombo->lineEdit(), SIGNAL(returnPressed()), this, SLOT(replaceChecked()));
320 321 322



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

325 326
    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
327
    connect(&m_searchOpenFiles, SIGNAL(searchDone()),  this, SLOT(searchDone()));
328
    connect(&m_searchOpenFiles, SIGNAL(searching(QString)), this, SLOT(searching(QString)));
Kåre Särs's avatar
Kåre Särs committed
329

330
    connect(&m_folderFilesList, SIGNAL(finished()),  this, SLOT(folderFileListChanged()));
331

332 333
    connect(&m_searchDiskFiles, SIGNAL(matchFound(QString,QString,int,int,QString,int)),
            this,                 SLOT(matchFound(QString,QString,int,int,QString,int)));
334
    connect(&m_searchDiskFiles, SIGNAL(searchDone()),  this, SLOT(searchDone()));
335
    connect(&m_searchDiskFiles, SIGNAL(searching(QString)), this, SLOT(searching(QString)));
336

337
    connect(m_kateApp, SIGNAL(documentWillBeDeleted(KTextEditor::Document*)),
338
            &m_searchOpenFiles, SLOT(cancelSearch()));
339

340
    connect(m_kateApp, SIGNAL(documentWillBeDeleted(KTextEditor::Document*)),
341 342
            &m_replacer, SLOT(cancelReplace()));

343
    connect(m_kateApp, SIGNAL(documentWillBeDeleted(KTextEditor::Document*)),
344 345
            this, SLOT(clearDocMarks(KTextEditor::Document*)));

346 347 348
    connect(&m_replacer, SIGNAL(matchReplaced(KTextEditor::Document*,int,int,int)),
            this, SLOT(addMatchMark(KTextEditor::Document*,int,int,int)));

349 350 351 352
    // Hook into line edit context menus
    m_ui.searchCombo->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(m_ui.searchCombo, SIGNAL(customContextMenuRequested(QPoint)), this,
            SLOT(searchContextMenu(QPoint)));
353 354 355 356 357 358 359 360 361
    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);
362

363
    connect(m_mainWindow, SIGNAL(unhandledShortcutOverride(QEvent*)),
364 365
            this, SLOT(handleEsc(QEvent*)));

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

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

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


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

380
    m_replacer.setDocumentManager(m_kateApp);
381
    connect(&m_replacer, SIGNAL(replaceDone()), this, SLOT(replaceDone()));
382

383 384
    searchPlaceChanged();

385 386
    m_toolView->installEventFilter(this);

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

KatePluginSearchView::~KatePluginSearchView()
{
392 393
    clearMarks();

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

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

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

416 417 418 419 420 421 422 423 424 425 426 427

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

609

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

614
    const bool inFolder = (m_ui.searchPlaceCombo->currentIndex() == 1);
615 616
    const bool inCurrentProject = (m_ui.searchPlaceCombo->currentIndex() == 2);
    const bool inAllOpenProjects = (m_ui.searchPlaceCombo->currentIndex() == 3);
617

618
    m_ui.filterCombo->setEnabled(inFolder || inCurrentProject || inAllOpenProjects);
619

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

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

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

649 650 651 652 653
    QUrl fullUrl = QUrl::fromUserInput(url);
    QString path = fullUrl.isLocalFile() ? localFileDirUp (fullUrl).path() : fullUrl.url();
    if (!path.isEmpty() && !path.endsWith(QLatin1Char('/'))) {
        path += QLatin1Char('/');
    }
654
    path.replace(m_resultBaseDir, QString());
655
    QString name = fullUrl.fileName();
656 657 658
    if (url.isEmpty()) {
        name = fName;
    }
659

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    m_curResults->matches++;

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

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

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

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

848 849 850
void KatePluginSearchView::startSearch()
{
    m_changeTimer.stop(); // make sure not to start a "while you type" search now
851
    m_mainWindow->showToolView(m_toolView); // in case we are invoked from the command interface
852 853 854 855 856 857
    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;
    }
858 859 860 861 862 863 864

    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) {
865 866 867
        m_ui.filterCombo->insertItem(0, m_ui.filterCombo->currentText());
        m_ui.filterCombo->setCurrentIndex(0);
    }