summaryrefslogtreecommitdiffstats
path: root/src/kile/kilegrepdialog.cpp
blob: 24beb0da8731d824e2156824fa38cc1ae15956f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
/* This file is part of the kile project
   Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org>
   Copyright (C) 2001 Joseph Wenninger <jowenn@kde.org>
   Copyright (C) 2001 Anders Lund <anders.lund@lund.tdcadsl.dk>
   Copyright (C) 2003 Jan-Marek Glogowski <glogow@stud.fbi.fh-darmstadt.de>
   Copyright (C) 2005 Holger Danielsson <holger.danielsson@versanet.de>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Steet, Fifth Floor,
   Boston, MA 02110-1301, USA.

   Original from kdebase / kate

   changes: 2005-11-27 (dani)
    - add a search for all files of a Kile project
      (done with one grep command for each file)
    - dialog is now based on KDialogBase
    - an item of the resultbox ist opened when it's highlightened 
      (no double click is needed anymore)
    - dialog is deleted after work to minimize resources
    - added additional search modes for environments, labels etc.
    - fixed some bugs (f.e. two slashes at the end of directory 
      names, jumping to the wrong line, wrong pattern lists)
    - add some editable template modes to search for LaTeX commands
    - add some predined modes to search for environments, graphics,
      labels, and references, either all of them or some special ones

    (in other words: most parts have changed to work perfectly with Kile ...)
*/

// 2007-03-12 dani
//  - use KileDocument::Extensions

#include "kilegrepdialog.h"

#include <tqobject.h>
#include <tqlayout.h>
#include <tqpushbutton.h>
#include <tqlineedit.h>
#include <tqlabel.h>
#include <tqcheckbox.h>
#include <tqevent.h>
#include <tqregexp.h>
#include <tqwhatsthis.h>
#include <tqcursor.h>

#include <kcombobox.h>
#include <kapplication.h>
#include <kaccelmanager.h>
#include <kbuttonbox.h>
#include <kfiledialog.h>
#include <kprocess.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <kurlrequester.h>
#include <kurlcompletion.h>
#include <klineedit.h>
#include <klistbox.h>
#include "kiledebug.h"

#include "kileconfig.h"
#include "kileproject.h"
#include "kiledocmanager.h"
#include "kileextensions.h"

KileGrepDialog::KileGrepDialog(TQWidget *tqparent, KileInfo *ki, KileGrep::Mode mode, const char *name)
	: KDialogBase (tqparent, name, false, TQString(), 0, Ok, false ), 
	  m_ki(ki), m_mode(mode), childproc(0), m_grepJobs(0)
{
	TQWidget *page = new TQWidget(this);
	setMainWidget(page);
	//setWFlags( TQt::WStyle_StaysOnTop );

	// build dialog
	TQVBoxLayout *vbox = new TQVBoxLayout( page,5,KDialog::spacingHint() );

	// project groupbox
	TQGroupBox *projectgroup = new TQGroupBox( i18n("Project"),page); 
	projectgroup->setColumnLayout(0, Qt::Vertical );
	projectgroup->tqlayout()->setSpacing( 6 );
	projectgroup->tqlayout()->setMargin( 11 );
	TQGridLayout *projectgrouptqlayout = new TQGridLayout( projectgroup->tqlayout() );
	projectgrouptqlayout->tqsetAlignment( TQt::AlignTop );

	TQLabel *project_label = new TQLabel(i18n("Name:"), projectgroup);
	int labelwidth = project_label->tqsizeHint().width();

	TQLabel *projectdir_label = new TQLabel(i18n("Directory:"), projectgroup);
	if ( projectdir_label->tqsizeHint().width() > labelwidth )
		labelwidth = projectdir_label->tqsizeHint().width();

	projectname_label = new TQLabel(projectgroup);
	projectdirname_label = new TQLabel(projectgroup);

	projectgrouptqlayout->addWidget(project_label, 0,0, AlignLeft | AlignVCenter);
	projectgrouptqlayout->addWidget(projectname_label, 0,1, AlignLeft | AlignVCenter);
	projectgrouptqlayout->addWidget(projectdir_label, 1,0, AlignLeft | AlignVCenter);
	projectgrouptqlayout->addWidget(projectdirname_label, 1,1, AlignLeft | AlignVCenter);
	projectgrouptqlayout->setColStretch(1,1);

	// search groupbox
	TQGroupBox *searchgroup = new TQGroupBox( i18n("Search"),page); 
	searchgroup->setColumnLayout(0, Qt::Vertical );
	searchgroup->tqlayout()->setSpacing( 6 );
	searchgroup->tqlayout()->setMargin( 11 );
	TQGridLayout *searchgrouptqlayout = new TQGridLayout( searchgroup->tqlayout() );
	searchgrouptqlayout->tqsetAlignment( TQt::AlignTop );

	TQLabel *pattern_label = new TQLabel(i18n("Pattern:"), searchgroup);
	if ( pattern_label->tqsizeHint().width() > labelwidth )
		labelwidth = pattern_label->tqsizeHint().width();

	pattern_combo = new KComboBox(true, searchgroup);
	pattern_combo->setInsertionPolicy(KComboBox::NoInsertion);
	pattern_combo->setFocus();
	pattern_combo->setMinimumSize(pattern_combo->tqsizeHint());
	pattern_label->setBuddy(pattern_combo);

	TQLabel *template_label = new TQLabel(i18n("Template:"), searchgroup);
	if ( template_label->tqsizeHint().width() > labelwidth )
		labelwidth = template_label->tqsizeHint().width();

	TQStringList templatemode_list;
	templatemode_list << i18n("Normal") 
	                  << i18n("Command") 
	                  << i18n("Command[]") 
	                  << i18n("Environment") 
	                  << i18n("Image")
	                  << i18n("Label") 
	                  << i18n("Reference")
	                  << i18n("File")
	                  ;

	TQBoxLayout *template_layout = new TQHBoxLayout(4);
	template_combo = new KComboBox(false, searchgroup);
	template_combo->insertStringList(templatemode_list);
	template_combo->adjustSize();
	template_combo->setFixedSize(template_combo->size());
	template_layout->addWidget(template_combo);
	m_lastTemplateIndex = 0;

	template_edit = new KLineEdit(searchgroup);
	template_edit->setText("%s");
	template_edit->setMinimumSize(template_edit->tqsizeHint());
	template_label->setBuddy(template_edit);
	template_layout->addWidget(template_edit);

	searchgrouptqlayout->addWidget(pattern_label, 0,0, AlignLeft | AlignVCenter);
	searchgrouptqlayout->addWidget(pattern_combo, 0,1);
	searchgrouptqlayout->addWidget(template_label, 1,0, AlignLeft | AlignVCenter);
	searchgrouptqlayout->addLayout(template_layout, 1,1);

	// filter groupbox
	TQGroupBox *filtergroup = new TQGroupBox( i18n("Directory Options"),page); 
	filtergroup->setColumnLayout(0, Qt::Vertical );
	filtergroup->tqlayout()->setSpacing( 6 );
	filtergroup->tqlayout()->setMargin( 11 );
	TQGridLayout *filtergrouptqlayout = new TQGridLayout( filtergroup->tqlayout() );
	filtergrouptqlayout->tqsetAlignment( TQt::AlignTop );

	TQLabel *files_label = new TQLabel(i18n("Filter:"), filtergroup);
	if ( files_label->tqsizeHint().width() > labelwidth )
		labelwidth = files_label->tqsizeHint().width();

	filter_combo = new KComboBox(true, filtergroup);
	filter_combo->setMinimumSize(filter_combo->tqsizeHint());
	files_label->setBuddy(TQT_TQWIDGET(filter_combo->focusProxy()));

	TQLabel *dir_label = new TQLabel(i18n("Directory:"), filtergroup);
	if ( dir_label->tqsizeHint().width() > labelwidth )
		labelwidth = dir_label->tqsizeHint().width();

	TQBoxLayout *dir_layout = new TQHBoxLayout(3);
	dir_combo = new KURLRequester( new KComboBox(true, filtergroup), filtergroup, "dir combo" );
	dir_combo->completionObject()->setMode(KURLCompletion::DirCompletion);
	dir_combo->setMode(KFile::Directory|KFile::LocalOnly|KFile::ExistingOnly);
	dir_label->setBuddy(dir_combo);
	dir_layout->addWidget(dir_combo);

	recursive_box = new TQCheckBox(i18n("Scan directories recursively"), filtergroup);
	recursive_box->setMinimumWidth(recursive_box->tqsizeHint().width());

	filtergrouptqlayout->addWidget(files_label, 2,0, AlignLeft | AlignVCenter);
	filtergrouptqlayout->addWidget(filter_combo, 2, 1);
	filtergrouptqlayout->addWidget(dir_label, 3,0, AlignLeft | AlignVCenter);
	filtergrouptqlayout->addLayout(dir_layout, 3,1);
	filtergrouptqlayout->addMultiCellWidget(recursive_box, 4,4, 1,2);
	filtergrouptqlayout->setColStretch(1,1);

	// result box
	resultbox = new KListBox(page);
	resultbox->setMinimumHeight(150);

	// button box
	KButtonBox *actionbox = new KButtonBox(page, Qt::Horizontal);
	search_button = actionbox->addButton(i18n("&Search"));
	search_button->setDefault(true);
	search_button->setEnabled(false);
	clear_button = actionbox->addButton(i18n("&Clear"));
	clear_button->setEnabled(false);
	actionbox->addStretch();
#if KDE_VERSION >= KDE_MAKE_VERSION(3,3,0)
	close_button = actionbox->addButton(KStdGuiItem::close());
#else
        close_button = actionbox->addButton(i18n("Cl&ose"));
#endif
	actionbox->tqlayout();

	// adjust labels
	project_label->setFixedWidth(labelwidth);
	projectdir_label->setFixedWidth(labelwidth);
	pattern_label->setFixedWidth(labelwidth);
	template_label->setFixedWidth(labelwidth);
	files_label->setFixedWidth(labelwidth);
	dir_label->setFixedWidth(labelwidth);

	if ( m_mode == KileGrep::Project )
	{
		filtergroup->hide();
		vbox->addWidget(projectgroup); 
		vbox->addWidget(searchgroup);
	}
	else
	{
		projectgroup->hide();
		vbox->addWidget(searchgroup);
		vbox->addWidget(filtergroup); 
	}
	vbox->addWidget(resultbox);
	vbox->addWidget(actionbox);

	// Produces error messages like
	// TQListBox::property( "text" ) failed:
	// 	property invalid or does not exist
	// Anyone an idea?
	KAcceleratorManager::manage( this );

	TQWhatsThis::add(pattern_combo,
		i18n("Enter the regular expression you want to search for here.<br>"
		 "Possible meta characters are:<br>"
		 "<ul>"
		 "<li>&nbsp;<b>.</b> - Matches any character</li>"
		 "<li>&nbsp;<b>^</b> - Matches the beginning of a line</li>"
		 "<li>&nbsp;<b>$</b> - Matches the end of a line</li>"
		 "<li>&nbsp;<b>\\\\\\&lt;</b> - Matches the beginning of a word</li>"
		 "<li>&nbsp;<b>\\\\\\&gt;</b> - Matches the end of a word</li>"
		 "</ul>"
		 "The following repetition operators exist:"
		 "<ul>"
		 "<li>&nbsp;<b>?</b> - The preceding item is matched at most once</li>"
		 "<li>&nbsp;<b>*</b> - The preceding item is matched zero or more times</li>"
		 "<li>&nbsp;<b>+</b> - The preceding item is matched one or more times</li>"
		 "<li>&nbsp;<b>{<i>n</i>}</b> - The preceding item is matched exactly <i>n</i> times</li>"
		 "<li>&nbsp;<b>{<i>n</i>,}</b> - The preceding item is matched <i>n</i> or more times</li>"
		 "<li>&nbsp;<b>{,<i>n</i>}</b> - The preceding item is matched at most <i>n</i> times</li>"
		 "<li>&nbsp;<b>{<i>n</i>,<i>m</i>}</b> - The preceding item is matched at least <i>n</i>, "
		 "but at most <i>m</i> times.</li>"
		 "</ul>"
		 "Furthermore, backreferences to bracketed subexpressions are "
		 "available via the notation \\\\<i>n</i>."
		 ));
	TQWhatsThis::add(filter_combo,
		i18n("Enter the file name pattern of the files to search here. "
		 "You may give several patterns separated by commas."));
	TQWhatsThis::add(template_combo,
		i18n("Choose one search mode. For the first modes, the search pattern is "
		 "build from the editable template, where '%s' is replaced by the given pattern.<br><br>"
		 "There are additional fixed predefined modes for environments, graphics, labels, references "
		 "and input files. If the pattern is empty, Kile will search for all commands of this mode. "
		 "If a pattern is given, it will be inserted as a parameter. F.e., in environment mode with "
		 "pattern 'center', Kile will search for '\\begin{center}' and in graphics mode with "
		 "pattern '.*\\.png', Kile will search for all png files."));
	TQWhatsThis::add(template_edit,
		i18n("For the first three modes you can choose a template for the pattern from the combo box "
		 "and edit it here. The string %s in the template is replaced "
		 "by the pattern input field, resulting in the regular expression "
		 "to search for. In all other modes this template is ignored."));
	TQWhatsThis::add(dir_combo,
		i18n("Enter the directory which contains the files you want to search in."));
	TQWhatsThis::add(recursive_box,
		i18n("Check this box to search in all subdirectories."));
	TQWhatsThis::add(resultbox,
		i18n("The results of the grep run are listed here. Select a "
		 "filename/line number combination with a mouse click on the item "
		 "or with the cursor to show the respective line in the editor."));

	// read config and setup dialog for both modes
	readConfig();
	if ( m_mode == KileGrep::Directory )
	{
		setCaption(i18n("Find in Files"));
		setupDirectory();
	}
	else
	{
		setCaption(i18n("Find in Project"));
		setupProject();
	}
 
	pattern_combo->setEditText(TQString());
	template_edit->setText(template_list[0]);
	slotPatternTextChanged(TQString());

	connect( pattern_combo->lineEdit(), TQT_SIGNAL(textChanged ( const TQString & )),
		TQT_SLOT( slotPatternTextChanged( const TQString & )));
	connect( template_combo, TQT_SIGNAL(activated(int)),
		TQT_SLOT(slotTemplateActivated(int)) );
	connect( resultbox, TQT_SIGNAL(highlighted(const TQString&)),
		TQT_SLOT(slotItemSelected(const TQString&)) );

	connect( search_button, TQT_SIGNAL(clicked()), TQT_SLOT(slotSearch()) );
	connect( clear_button,  TQT_SIGNAL(clicked()), TQT_SLOT(slotClear()) );
	connect( close_button,  TQT_SIGNAL(clicked()), TQT_SIGNAL(closeClicked()) );

	connect( this, TQT_SIGNAL(closeClicked()), TQT_SLOT(slotClose()) );
	connect( this, TQT_SIGNAL(finished()), TQT_SLOT(slotFinished()) );

	resize(450,tqsizeHint().height());
	KILE_DEBUG() << "==KileGrepDialog (create dialog)=============================" << endl;
}

KileGrepDialog::~KileGrepDialog()
{
	KILE_DEBUG() << "==KileGrepDialog (delete dialog)=============================" << endl;
	writeConfig();
	delete childproc;
}

///////////////////// config /////////////////////

void KileGrepDialog::readConfig()
{
	pattern_combo->insertStringList( readList(KileGrep::SearchItems) );

	TQString labels = getCommandList(KileDocument::CmdAttrLabel);
	TQString references = getCommandList(KileDocument::CmdAttrReference);
	template_list = readList(KileGrep::SearchTemplates) ;
	if ( template_list.count() != 3 )
	{
		template_list.clear();
		template_list << "%s" << "\\\\%s\\{" << "\\\\%s(\\[[^]]*\\])?\\{";
	}
	template_list << "\\\\begin\\{"                             // to be closed with "%s\\}"
	              << "\\\\includegraphics(\\[[^]]*\\])?\\{"
	              << "\\\\(label" + labels + ")\\{"
	              << "\\\\(ref|pageref|vref|vpageref|fref|Fref|eqref" + references + ")(\\[[^]]*\\])?\\{"
	              << "\\\\(input|include)\\{"
	              ;
	
	if ( m_mode == KileGrep::Directory )
	{
		dir_combo->comboBox()->insertStringList( readList(KileGrep::SearchPaths) );
		recursive_box->setChecked( KileConfig::grepRecursive() );
	}
}

void KileGrepDialog::writeConfig()
{
	KileConfig::setLastSearchItems( getListItems(pattern_combo) );

	TQStringList list;
	list << template_list[0] << template_list[1] << template_list[2];
	KileConfig::setLastSearchTemplates( list );

	if ( m_mode == KileGrep::Directory )
	{
		KileConfig::setLastSearchPaths( getListItems(dir_combo->comboBox()) );
		KileConfig::setGrepRecursive( recursive_box->isChecked() );
	}
}

///////////////////// setup search modes /////////////////////

void KileGrepDialog::setupDirectory()
{
	setDirName( TQDir::home().absPath() );

	// use a filter for 'find in files' dialog
	KileDocument::Extensions *extensions = m_ki->extensions();
	TQString filter = extensions->latexDocumentFileFilter() + '\n'
	                 + extensions->latexPackageFileFilter() + '\n'
	                 + extensions->bibtexFileFilter() + '\n'
	                 + extensions->metapostFileFilter() + '\n'
	                 + "*|" + i18n("All Files");
	setFilter(filter);
}

void KileGrepDialog::setupProject()
{
	KileProject *project = m_ki->docManager()->activeProject();
	if ( project )
	{
		m_projectOpened = true;
		m_projectdir = project->baseURL().path();
		projectname_label->setText( project->name() );
		projectdirname_label->setText( m_projectdir );

		m_projectfiles.clear();
		m_projectfiles = m_ki->docManager()->getProjectFiles();
	}
	else
	{
		m_projectOpened = false;
		projectname_label->setText( i18n("no project opened") );
		projectdirname_label->setText( TQString() );
	}
}

///////////////////// read entries /////////////////////

TQStringList KileGrepDialog::readList(KileGrep::List listtype)
{
	TQStringList strings,result;

	bool stripSlash = false;
	switch ( listtype )
	{
		case KileGrep::SearchItems: 
			strings = KileConfig::lastSearchItems(); 
			break;
		case KileGrep::SearchPaths: 
			strings = KileConfig::lastSearchPaths(); 
			stripSlash = true;
			break;
		case KileGrep::SearchTemplates: 
			strings = KileConfig::lastSearchTemplates(); 
			break;
	}

	while (strings.count() > 0) 
	{
		if ( stripSlash && strings[0].right(1)=="/" )
			strings[0].truncate( strings[0].length()-1 );
		if ( ! strings[0].isEmpty() )
			result.append(strings[0]);
		strings.remove(strings[0]);
	}
	return result;
}

///////////////////// item selected /////////////////////

void KileGrepDialog::slotItemSelected(const TQString& item)
{
	KILE_DEBUG() << "\tgrep: start item selected" << endl;
	int pos;
	TQString filename, linenumber;

	TQString str = item;
	if ( (pos = str.find(':')) != -1)
	{
		filename = str.left(pos);
		str = str.right(str.length()-1-pos);
		if ( (pos = str.find(':')) != -1)
		{
			linenumber = str.left(pos);
			if ( m_mode == KileGrep::Project )
				emit itemSelected(m_projectdir + '/' + filename,linenumber.toInt());
			else
				//emit itemSelected(lastSearchPaths[0] + "/" + filename,linenumber.toInt());
				emit itemSelected(dir_combo->comboBox()->text(0) + '/' + filename,linenumber.toInt());
		}
	}
}

///////////////////// grep /////////////////////

void KileGrepDialog::startGrep()
{
	childproc = new KProcess();
	childproc->setUseShell(true);

	if ( m_mode == KileGrep::Project )
	{
		TQString command = buildProjectCommand() + ' ' + KProcess::quote(m_projectfiles[m_grepJobs-1]);
		KILE_DEBUG() << "\tgrep (project): " <<  command << endl;
		(*childproc) << TQStringList::split(' ',command);
	}
	else
	{
		TQString command = buildFilesCommand();
		KILE_DEBUG() << "\tgrep (files): " << command << endl;
		(*childproc) << TQStringList::split(' ', command);
	}
	m_grepJobs--;

	connect( childproc, TQT_SIGNAL(processExited(KProcess *)),
		TQT_SLOT(childExited()) );
	connect( childproc, TQT_SIGNAL(receivedStdout(KProcess *, char *, int)),
		TQT_SLOT(receivedOutput(KProcess *, char *, int)) );
	connect( childproc, TQT_SIGNAL(receivedStderr(KProcess *, char *, int)),
		TQT_SLOT(receivedErrOutput(KProcess *, char *, int)) );

	childproc->start(KProcess::NotifyOnExit, KProcess::AllOutput);
}

void KileGrepDialog::processOutput()
{
	int pos;
	while ( (pos = buf.find('\n')) != -1)
	{
		TQString item = buf.left(pos);
		if ( ! item.isEmpty() )
		{
			if ( m_mode == KileGrep::Project )
			{
				if ( item.find(m_projectdir + '/') == 0 )
					resultbox->insertItem( item.mid(m_projectdir.length()+1) );
				else
					resultbox->insertItem(item);
			}
			else
			{
				resultbox->insertItem( item.mid(dir_combo->url().length()+1) );
			}
		}
		buf = buf.right(buf.length()-pos-1);
	}
	kapp->processEvents();
}

void KileGrepDialog::receivedOutput(KProcess */*proc*/, char *buffer, int buflen)
{
	buf += TQString::fromLocal8Bit(buffer, buflen);
	processOutput();
}

void KileGrepDialog::receivedErrOutput(KProcess */*proc*/, char *buffer, int buflen)
{
	errbuf += TQString::fromLocal8Bit( buffer, buflen );
}

void KileGrepDialog::childExited()
{
//	 int status = childproc->exitStatus();

	if ( ! errbuf.isEmpty() )
	{
		KMessageBox::information( parentWidget(),
			i18n("<strong>Error:</strong><p>") + errbuf,
			i18n("Grep Tool Error") );
		errbuf.truncate(0);
	}
	else
		finish();
}

void KileGrepDialog::finish()
{
	buf += '\n';
	processOutput();
	if ( childproc )
	{
		delete childproc;
		childproc = 0;
	}

	if ( shouldRestart() )
	{
		startGrep();
	}
	else
	{
		updateLists();

		resultbox->unsetCursor();
		clear_button->setEnabled( resultbox->count() > 0 );
		search_button->setText( i18n("&Search") );
		slotPatternTextChanged( pattern_combo->lineEdit()->text() );
	}
}

void KileGrepDialog::updateLists()
{
	updateListItems(pattern_combo);
	if ( m_mode==KileGrep::Directory )
	{
		updateListItems(dir_combo->comboBox());
	}
}

///////////////////// build commands /////////////////////

TQString KileGrepDialog::getPattern()
{
	TQString pattern;
	int template_mode = template_combo->currentItem();
	if ( template_mode < KileGrep::tmEnv )
	{
		pattern = template_edit->text();
		if ( pattern.isEmpty() )
			pattern = pattern_combo->currentText();
		else
			pattern.replace("%s", pattern_combo->currentText());
	}
	else
	{
		pattern = template_list[template_mode];
		if ( ! pattern_combo->currentText().isEmpty() )
			pattern += pattern_combo->currentText()  + "\\}";
	}

	return pattern;
}

TQString KileGrepDialog::getShellPattern()
{
	TQString pattern = getPattern();
	pattern.replace("'", "'\\''");
	return '\'' + pattern + '\'';
	//return KProcess::quote(pattern);
}


TQString KileGrepDialog::buildFilesCommand()
{
	TQString files, files_temp;

	if (filter_combo->currentItem() >= 0)
		files_temp = filter_list[filter_combo->currentItem()];
	else
		files_temp = filter_combo->currentText();

	if (files_temp.right(1) != ",")
		files_temp = files_temp + ',';

	TQStringList tokens = TQStringList::split ( ",", files_temp, false );
	TQStringList::Iterator it = tokens.begin();
	if (it != tokens.end())
	{
		files = " '" + (*it) + '\'';
		++it;
	}

	for ( ; it != tokens.end(); ++it )
		files = files + " -o -name " + '\'' + (*it) + '\'';

	TQString shell_command;
	shell_command += "find ";
	shell_command += KProcess::quote(dir_combo->url());
	shell_command += " \\( -name ";
	shell_command += files;
	shell_command += " \\)";
	if (!recursive_box->isChecked())
		shell_command += " -maxdepth 1";
	shell_command += " -exec grep -n -E -I -H -e " + getShellPattern() + " {} \\;";

	return shell_command;
}

TQString KileGrepDialog::buildProjectCommand()
{
	return "grep -n -E -I -H -e " + getShellPattern();
}

///////////////////// Search /////////////////////

void KileGrepDialog::slotSearch()
{
	KILE_DEBUG() << "\tgrep: start slot search" << endl;
	slotClear ();

	if ( template_combo->currentItem()<KileGrep::tmEnv && pattern_combo->currentText().isEmpty() )
		return;

	if ( childproc && childproc->isRunning() )
	{
		childproc->kill();
		return;
	}

	KILE_DEBUG() << "\tgrep: start new search" << endl;
	TQRegExp re( getPattern() );
	if ( ! re.isValid() )
	{
		KMessageBox::error( 0, i18n("Invalid regular expression: %1").tqarg(re.errorString()), i18n("Grep Tool Error") );
		return;
	}

	resultbox->setCursor( TQCursor(TQt::WaitCursor) );
	search_button->setText( i18n("&Cancel") );
	if ( template_combo->currentItem() < KileGrep::tmEnv)
		template_list[m_lastTemplateIndex] = template_edit->text();

	// start grep command
	m_grepJobs = ( m_mode == KileGrep::Project ) ? m_projectfiles.count() : 1;
	startGrep();
}

void KileGrepDialog::slotSearchFor(const TQString &pattern)
{
	slotClear();
	pattern_combo->setEditText(pattern);
	slotSearch();
}

void KileGrepDialog::slotClear()
{
	//KILE_DEBUG() << "\tgrep: slot clear" << endl;
	clearGrepJobs();
	resultbox->clear();
	finish();
}

void KileGrepDialog::slotClose()
{
	//KILE_DEBUG() << "\tgrep: slot close" << endl;
	clearGrepJobs();
	finish();
	delayedDestruct();
}

void KileGrepDialog::slotFinished()
{
	//KILE_DEBUG() << "\tgrep: slot finished" << endl;
	finish();
	delayedDestruct();
}

///////////////////// templates /////////////////////

void KileGrepDialog::slotPatternTextChanged(const TQString &)
{
	updateWidgets();
}

void KileGrepDialog::slotTemplateActivated(int index)
{
	if ( index < KileGrep::tmEnv)
	{
		template_list[m_lastTemplateIndex] = template_edit->text();
		template_edit->setText( template_list[index] );
	}
	else
	{
		template_edit->setText(TQString());
	}
	m_lastTemplateIndex = index;

	updateWidgets();
}

void KileGrepDialog::updateWidgets()
{
	bool search_state = (m_mode==KileGrep::Directory) || (m_mode==KileGrep::Project && m_projectOpened);

	if ( template_combo->currentItem()  < KileGrep::tmEnv )
	{
		template_edit->setEnabled(true);
		search_button->setEnabled( search_state && !pattern_combo->currentText().isEmpty() );
	}
	else
	{
		template_edit->setEnabled(false);
		search_button->setEnabled( search_state );
	}
}

///////////////////// directory /////////////////////

void KileGrepDialog::setDirName(const TQString &dir)
{
	KComboBox *combo = dir_combo->comboBox();

	if ( findListItem(combo,dir) < 0 )
		combo->insertItem(dir);
	if ( combo->text(0) != dir)
		slotClear();
}

///////////////////// filter /////////////////////

void KileGrepDialog::setFilter(const TQString &filter)
{
	filter_list.clear();
	filter_combo->clear();
	if ( !filter.isEmpty() )
	{
		TQStringList filter_lst = TQStringList::split("\n", filter);
		for (TQStringList::Iterator it = filter_lst.begin();
			it != filter_lst.end(); ++it)
		{
			TQStringList filter_split = TQStringList::split("|", *it);
			filter_list.append(filter_split[0]);
			filter_combo->insertItem(filter_split[1]);
		}
	}
}

void KileGrepDialog::appendFilter(const TQString &name, const TQString &filter)
{
	filter_combo->insertItem(name);
	filter_list.append(filter);
}

///////////////////// template /////////////////////

void KileGrepDialog::appendTemplate(const TQString &name, const TQString &regexp)
{
	template_combo->insertItem(name);
	template_list.append(regexp);
}

void KileGrepDialog::clearTemplates()
{
	template_combo->clear();
	template_list.clear();
}

///////////////////// KComboBox /////////////////////

TQStringList KileGrepDialog::getListItems(KComboBox *combo)
{
	TQStringList list;
	for ( int i=0; i<combo->count() && i<KILEGREP_MAX; ++i )
		list.append( combo->text(i) );
	return list;
}

int KileGrepDialog::findListItem(KComboBox *combo, const TQString &s)
{
	for ( int i=0; i<combo->count(); ++i )
	{
		if ( combo->text(i) == s )
			return i;
	}
	return -1;
}

void KileGrepDialog::updateListItems(KComboBox *combo)
{
	TQString s = combo->currentText();
	if ( s.isEmpty() )
		return;

	int index = findListItem(combo,s);
	if ( index > 0 )                               // combo already contains s
	{
		combo->removeItem(index);                   // remove this item
	}
	else if ( index == -1 )                        // combo doesn't contain s
	{
		if ( combo->count() >= KILEGREP_MAX )
			combo->removeItem( combo->count()-1 );   // remove last item
	}

	if ( index != 0 )
	{
		combo->insertItem(s,0);                     // insert this item as first item
		combo->setCurrentItem(0);                   // and select it
	}
}

///////////////////// template /////////////////////

TQString KileGrepDialog::getCommandList(KileDocument::CmdAttribute attrtype)
{
	TQStringList cmdlist;
	TQStringList::ConstIterator it;

	// get info about user defined references
	KileDocument::LatexCommands *cmd = m_ki->latexCommands();
	cmd->commandList(cmdlist,attrtype,true);

	// build list of references
	TQString commands = TQString();
	for ( it=cmdlist.begin(); it != cmdlist.end(); ++it ) 
	{
		commands += '|' + (*it).mid(1);
	}
	return commands;
}


#include "kilegrepdialog.moc"