summaryrefslogtreecommitdiffstats
path: root/src/modules/editor/scripteditor.cpp
blob: f68752656ec2d5e4655241059e5fae8670d4df3e (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
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
//=============================================================================
//		
//   File : scripteditor.cpp
//   Created on Sun Mar 28 1999 16:11:48 CEST by Szymon Stefanek
//	 Code improvements by Carbone Alessandro & Tonino Imbesi
//
//   This file is part of the KVIrc IRC client distribution
//   Copyright (C) 1999-2004 Szymon Stefanek <pragma at kvirc dot net>
//
//   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 opinion) 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. If not, write to the Free Software Foundation,
//   Inc. ,51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
//=============================================================================

#include "scripteditor.h"

#include <tqlayout.h>
#include <tqtoolbutton.h>
#include <kvi_tal_groupbox.h>
#include "kvi_tal_popupmenu.h"
#include "kvi_tal_scrollview.h"
#include <tqmessagebox.h>
#include <tqtimer.h>
#ifdef COMPILE_USE_QT4
	//#define TQSyntaxHighlighter Q3SyntaxHighlighter
#else
	#include <tqobjectlist.h>
#endif
#include <tqcursor.h>
#include <tqfont.h>
#include <tqrect.h>

#include "kvi_fileutils.h"
#include "kvi_locale.h"
#include "kvi_filedialog.h"
#include "kvi_qstring.h"
#include "kvi_config.h"
#include "kvi_module.h"
#include "kvi_pointerlist.h"
//
#include "kvi_app.h"
#include "kvi_console.h"
#include "kvi_window.h"
#include "kvi_iconmanager.h"
#include "kvi_kvs_kernel.h"

#include <tqlayout.h>


extern KviPointerList<KviScriptEditorImplementation> * g_pScriptEditorWindowList;
extern KviModule * g_pEditorModulePointer;


static TQColor g_clrBackground(255,255,255);
static TQColor g_clrNormalText(0,0,0);
static TQColor g_clrBracket(255,0,0);
static TQColor g_clrComment(0,120,0);
static TQColor g_clrFunction(0,17,255);
static TQColor g_clrKeyword(85,85,255);
static TQColor g_clrVariable(255,0,0);
static TQColor g_clrPunctuation(180,180,0);
static TQColor g_clrFind(0,0,0);

static TQFont g_fntNormal("Courier New",8);

KviCompletionBox::KviCompletionBox(TQWidget * parent)
: KviTalListBox(parent)
{
	setPaletteForegroundColor(TQColor(0,0,0));
	setPaletteBackgroundColor(TQColor(255,255,255));
#ifdef COMPILE_USE_QT4
	setHScrollBarMode(KviTalListBox::AlwaysOff);
#else
	setHScrollBarMode(TQScrollView::AlwaysOff);
#endif
	TQFont listfont=font();
	listfont.setPointSize(8);
	setFont(listfont);
	setVariableWidth(false);
	setFixedWidth(200);
	//completelistbox->setColumnMode(KviTalListBox::Variable);
	hide();
}

void KviCompletionBox::updateContents(TQString buffer)
{
	buffer=buffer.stripWhiteSpace();
	KviPointerList<TQString> list;
	clear();
	
	TQString szModule;
	TQChar* pCur = (TQChar *)buffer.ucs2();
	
	int pos=buffer.find('.');
	
	if(pos>0)
	{
		szModule=buffer.left(pos);
		if(szModule[0].unicode()=='$')
			szModule.remove(0,1);
	}
	
	if(pCur->unicode() == '$')
	{
		buffer.remove(0,1);
		if(!buffer.isEmpty())
		{
			if(szModule.isEmpty())
				KviKvsKernel::instance()->completeFunction(buffer,&list);
			else
				tqDebug("we need a module completion!");
			for ( TQString* szCurrent = list.first(); szCurrent; szCurrent = list.next() )
			{
				szCurrent->prepend('$');
				//szCurrent->append('(');
				insertItem(*szCurrent);
			}
		}
	}
	else
	{
		if(szModule.isEmpty())
			KviKvsKernel::instance()->completeCommand(buffer,&list);
		else
			tqDebug("we need a module completion!");
		for ( TQString* szCurrent = list.first(); szCurrent; szCurrent = list.next() )
		{
			szCurrent->append(' ');
			insertItem(*szCurrent);
		}
	}
//	tqDebug("%s %s %i %i",__FILE__,__FUNCTION__,__LINE__,count());
}

void KviCompletionBox::keyPressEvent(TQKeyEvent * e)
{
//	tqDebug("%s %s %i %x",__FILE__,__FUNCTION__,__LINE__,e->key());
	switch(e->key())
	{
		case TQt::Key_Escape:
			hide();
			setFocus();
			break;
		case TQt::Key_Return:
			break;
		default:
			if(!e->text().isEmpty())
			{
				e->ignore();
			}
		
	}
	KviTalListBox::keyPressEvent(e);
}

KviScriptEditorWidgetColorOptions::KviScriptEditorWidgetColorOptions(TQWidget * pParent)
: TQDialog(pParent)
{
	m_pSelectorInterfaceList = new KviPointerList<KviSelectorInterface>;
        m_pSelectorInterfaceList->setAutoDelete(false);
	setCaption(__tr2qs_ctx("Preferences","editor"));
	TQGridLayout * g = new TQGridLayout(this,3,3,4,4);

	KviFontSelector * f = new KviFontSelector(this,__tr2qs_ctx("Font:","editor"),&g_fntNormal,true);
	g->addMultiCellWidget(f,0,0,0,2);
	m_pSelectorInterfaceList->append(f);
	KviTalGroupBox * gbox = new KviTalGroupBox(1,Qt::Horizontal,__tr2qs("Colors" ),this);
	g->addMultiCellWidget(gbox,1,1,0,2);
	KviColorSelector * s = addColorSelector(gbox,__tr2qs_ctx("Background:","editor"),&g_clrBackground,true);
	s = addColorSelector(gbox,__tr2qs_ctx("Normal text:","editor"),&g_clrNormalText,true);
	s = addColorSelector(gbox,__tr2qs_ctx("Brackets:","editor"),&g_clrBracket,true);
	s = addColorSelector(gbox,__tr2qs_ctx("Comments:","editor"),&g_clrComment,true);
	s = addColorSelector(gbox,__tr2qs_ctx("Functions:","editor"),&g_clrFunction,true);
	s = addColorSelector(gbox,__tr2qs_ctx("Keywords:","editor"),&g_clrKeyword,true);
	s = addColorSelector(gbox,__tr2qs_ctx("Variables:","editor"),&g_clrVariable,true);
	s = addColorSelector(gbox,__tr2qs_ctx("Punctuation:","editor"),&g_clrPunctuation,true);
	s = addColorSelector(gbox,__tr2qs_ctx("Find:","editor"),&g_clrFind,true);
	
	TQPushButton * b = new TQPushButton(__tr2qs_ctx("&OK","editor"),this);
	b->setDefault(true);
	connect(b,TQT_SIGNAL(clicked()),this,TQT_SLOT(okClicked()));
	g->addWidget(b,2,1);

	b = new TQPushButton(__tr2qs_ctx("Cancel","editor"),this);
	connect(b,TQT_SIGNAL(clicked()),this,TQT_SLOT(reject()));
	g->addWidget(b,2,2);


	g->setRowStretch(0,1);
	g->setColStretch(0,1);
}

KviScriptEditorWidgetColorOptions::~KviScriptEditorWidgetColorOptions()
{
	delete m_pSelectorInterfaceList;
}

KviColorSelector * KviScriptEditorWidgetColorOptions::addColorSelector(TQWidget * pParent,const TQString & txt,TQColor * pOption,bool bEnabled)
{
	KviColorSelector * s = new KviColorSelector(pParent,txt,pOption,bEnabled);
	m_pSelectorInterfaceList->append(s);
		return s;
}

void KviScriptEditorWidgetColorOptions::okClicked()
{
	for(KviSelectorInterface * i = m_pSelectorInterfaceList->first();i;i = m_pSelectorInterfaceList->next())
	{
		i->commit();
	}

	accept();
}


KviScriptEditorWidget::KviScriptEditorWidget(TQWidget * pParent)
: KviTalTextEdit(pParent)
{
	setWordWrap(KviTalTextEdit::NoWrap);
	m_pParent=pParent;
	m_szHelp="Nothing";
	updateOptions();
	m_szFind="";
	completelistbox=new KviCompletionBox(this);
	connect (completelistbox,TQT_SIGNAL(selected(const TQString &)),this,TQT_SLOT(slotComplete(const TQString &)));
}

KviScriptEditorWidget::~KviScriptEditorWidget()
{

}

#ifdef COMPILE_USE_QT4
Q3PopupMenu * KviScriptEditorWidget::createPopupMenu( const TQPoint& pos )
#else
TQPopupMenu * KviScriptEditorWidget::createPopupMenu( const TQPoint& pos )
#endif
{
#ifdef COMPILE_USE_QT4
	Q3PopupMenu *pop=KviTalTextEdit::createPopupMenu(pos);
#else
	TQPopupMenu *pop=KviTalTextEdit::createPopupMenu(pos);
#endif
	pop->insertItem(__tr2qs("Context sensitive help"),this,TQT_SLOT(slotHelp()),TQt::CTRL+TQt::Key_H);
	pop->insertItem(__tr2qs("&Replace"),this,TQT_SLOT(slotReplace()),TQt::CTRL+TQt::Key_R);
	return pop;
}

void KviScriptEditorWidget::slotFind()
{
	m_szFind=((KviScriptEditorImplementation*)m_pParent)->getFindlineedit()->text();
	setText(text());
}

void KviScriptEditorWidget::slotReplace()
{
	KviScriptEditorReplaceDialog *dialog=new KviScriptEditorReplaceDialog(this,tqtr("Find & Repalce"));
	connect (dialog,TQT_SIGNAL(replaceAll(const TQString &,const TQString &)),m_pParent,TQT_SLOT(slotReplaceAll(const TQString &,const TQString &)));
	connect (dialog,TQT_SIGNAL(initFind()),m_pParent,TQT_SLOT(slotInitFind()));
	connect (dialog,TQT_SIGNAL(nextFind(const TQString &)),m_pParent,TQT_SLOT(slotNextFind(const TQString &)));
	if(dialog->exec()){};

}
void KviScriptEditorWidget::slotHelp()
{
	contextSensitiveHelp();
}


void KviScriptEditorWidget::updateOptions()
{
	setPaper(TQBrush(g_clrBackground));
	setFont(g_fntNormal);
	setColor(g_clrNormalText);
	
	TQPalette p = palette();
	p.setColor(TQColorGroup::Text,g_clrNormalText);
	setPalette(p);
	
#ifdef COMPILE_USE_QT4
	setTextFormat(TQt::PlainText);
#else
	setTextFormat(KviTalTextEdit::PlainText);
#endif
	
	// this will rehighlight everything
	setText(text()); // an "hack" to ensure Update all in the editor
	KviScriptSyntaxHighlighter *h = new KviScriptSyntaxHighlighter(this);
	(void)h;
	((KviScriptEditorImplementation*)m_pParent)->getFindlineedit()->setPaletteForegroundColor(g_clrFind);
}

void KviScriptEditorWidget::keyPressEvent(TQKeyEvent * e)
{
	if(e->state() == TQt::ControlButton)
	{
		switch(e->key())
		{
			case TQt::Key_B:
				insert("$b");
				return;
			case TQt::Key_K:
				insert("$k");
				return;
			case TQt::Key_O:
				insert("$o");
				return;
			case TQt::Key_U:
				insert("$u");
				return;
			case TQt::Key_Enter:
			case TQt::Key_Return:
			case TQt::Key_Backspace:
			case TQt::Key_PageUp:
				 e->ignore(); // allow the parent to process it
				 return;
			break;
		}
	}

	if(e->state() == TQt::ShiftButton)
	{
		if (e->key() == TQt::Key_Insert) 
		{
			completition();
			return;
		}
	}
	switch(e->key())
	{	
		case TQt::Key_Period:
		case TQt::Key_Left:
		case TQt::Key_Right:
			if(!completelistbox->isVisible()) completition(0);
			break;
		case TQt::Key_Up:
		case TQt::Key_Escape:
		case TQt::Key_PageUp:
		case TQt::Key_PageDown:
		case TQt::Key_End:
		case TQt::Key_Home:
			if(completelistbox->isVisible()) completelistbox->hide();
			break;
		case TQt::Key_Down:
			if(completelistbox->isVisible())
			{
				completelistbox->setFocus();
				completelistbox->setCurrentItem(0);
				return;
			}
			break;
		case TQt::Key_Return:
			KviTalTextEdit::keyPressEvent(e);
			int para,pos;
			getCursorPosition(&para,&pos);
			if(para > 0)
			{
				TQString szPrev=text(para-1);
				if(!szPrev.isEmpty())
				{
					if(szPrev.at(szPrev.length() - 1).unicode() == ' ')
						szPrev.remove(szPrev.length() - 1,1);
					TQString szCur;
					const TQChar * pCur = (const TQChar *)szPrev.ucs2();
					if(pCur)
					{
						while(pCur->unicode() && pCur->isSpace()) 
						{
							szCur.append(*pCur);
							pCur++;
						}
					}
					insertAt(szCur,para,0);
					setCursorPosition(para,szCur.length()+pos);
				}
//				tqDebug("|%i|",pos);
			}
			return;
		default:
			setFocus();
			break;
	}
	KviTalTextEdit::keyPressEvent(e);
	emit keyPressed();
	if(completelistbox->isVisible()) 
		completition(0);
}

void KviScriptEditorWidget::contentsMousePressEvent(TQMouseEvent *e)
{
	completelistbox->hide();
	if (e->button() == Qt::RightButton)
	{
//	bool bIsFirstWordInLine;
	TQString buffer;
	int para = paragraphAt(e->pos());
	int index=charAt(e->pos(),&para);
	buffer=this->text(para);
	getWordOnCursor(buffer,index);
	TQString tmp=buffer;
	KviPointerList<TQString> l;
	if (tmp.left(1) == "$")
	{	
		tmp.remove(0,1);
		KviKvsKernel::instance()->completeFunction(tmp,&l);
		if (l.count() != 1) buffer="";
		else buffer=*(l.at(0));
	}
	else
	{
		KviKvsKernel::instance()->completeCommand(tmp,&l);
		if (l.count() != 1) buffer="";
		else buffer=*(l.at(0));
	}
	//tqDebug (buffer);
	m_szHelp=buffer;
	}
	KviTalTextEdit::contentsMousePressEvent(e);

}

bool KviScriptEditorWidget::contextSensitiveHelp() const
{
	TQString buffer;
	int para,index;
	getCursorPosition(&para,&index);
	buffer=text(para);

	getWordOnCursor(buffer,index);

	/*
	TQString tmp=buffer;
	KviPointerList<TQString> * l;
	if(tmp.left(1) == "$")
	{
		tmp.remove(0,1);
		l = g_pUserParser->completeFunctionAllocateResult(tmp);
	} else {
		l = g_pUserParser->completeCommandAllocateResult(tmp);
	}
	
	bool bOk = false;
	if(l)
	{
		for(TQString * s = l->first();s;s = l->next())
		{
			if(KviTQString::equalCI(*s,buffer))
			{
				l->last();
				bOk = true;
			}
		}
	}
	g_pUserParser->freeCompletionResult(l);
	if(!bOk)return false;
	*/

	TQString parse;
	KviTQString::sprintf(parse,"timer -s (help,0){ help -s %Q; }",&buffer);
	tqDebug ("parsing %s",parse.latin1());
	KviKvsScript::run(parse,(KviWindow*)g_pApp->activeConsole());
	
	return true;
}


void KviScriptEditorWidget::getWordOnCursor(TQString &buffer,int index) const
{
	TQRegExp re("[ \t=,\\(\\)\"}{\\[\\]\r\n+-*><;@!]");
	//tqDebug("BUFFER IS %s",buffer.utf8().data());
	int start = buffer.findRev(re,index);
	int end = buffer.find(re,index);

	TQString tmp;
	if(start!=end)
	{
		if(start<0)start=0;
		else start++;
		if(end<0)end=index;
		tmp = buffer.mid(start,end-start);
	}
	buffer = tmp;
	//tqDebug("BUFFER NOW IS %s",buffer.utf8().data());
}

void KviScriptEditorWidget::completition(bool bCanComplete)
{
	int line,index;
	TQString buffer;
	TQString word;
	getCursorPosition(&line,&index);
	buffer=this->text(line);
	bool bIsFirstWordInLine;
	getWordBeforeCursor(buffer,index,&bIsFirstWordInLine);
	if(!buffer.isEmpty())
		completelistbox->updateContents(buffer);
	if (completelistbox->count() == 1) word=completelistbox->text(0);
	if (!word.isEmpty() && bCanComplete)
	{
		insert(word);
		completelistbox->hide();
	}
	if( completelistbox->count() == 0 )
		completelistbox->hide();
	else if(!completelistbox->isVisible())
	{
		if (completelistbox->count() <6) completelistbox->resize(completelistbox->width(),(completelistbox->count()*completelistbox->fontMetrics().height()+20));
		else completelistbox->resize(completelistbox->width(),6*completelistbox->fontMetrics().height()+20);
		int posy=paragraphRect(line).bottom();
		int posx=fontMetrics().width(this->text(line).left(index));
		completelistbox->move(posx,posy);
		completelistbox->show();
	}
}

void KviScriptEditorWidget::getWordBeforeCursor(TQString &buffer,int index,bool *bIsFirstWordInLine)
{
	TQString tmp = buffer.left(index);
	buffer=tmp;
	int idx = buffer.findRev(' ');
	int idx1 = buffer.findRev("=");
	int idx2 = buffer.findRev(','); 
	int idx3 = buffer.findRev('(');
	int idx4 = buffer.findRev('"');
	if(idx1 > idx) idx= idx1;	
	if(idx2 > idx)idx = idx2;
	if(idx3 > idx)idx = idx3;
	if(idx4 > idx)idx = idx4;
	*bIsFirstWordInLine = false;
	if(idx > -1)buffer.remove(0,idx);
	else
	{
		*bIsFirstWordInLine = true;
		buffer.insert(0," ");
	}

}

void KviScriptEditorWidget::slotComplete(const TQString &str)
{
	TQString complete=str;
	int line,index;
	getCursorPosition(&line,&index);
	TQString buffer;
	buffer=this->text(line);
	bool bIsFirstWordInLine;
	getWordBeforeCursor(buffer,index,&bIsFirstWordInLine);
	int len=buffer.length();
//	if (buffer[1].unicode() == '$') len --;
	complete.remove(0,len-1);
	if (buffer[1].unicode() == '$') complete.append("(");
	else complete.append(" ");
	insert (complete);
	completelistbox->hide();
	setFocus();
}

KviScriptSyntaxHighlighter::KviScriptSyntaxHighlighter(KviScriptEditorWidget * pWidget)
: TQSyntaxHighlighter(pWidget)
{
}

KviScriptSyntaxHighlighter::~KviScriptSyntaxHighlighter()
{
}

#define IN_COMMENT 1
#define IN_LINE 2
#define IN_STRING 4

int KviScriptSyntaxHighlighter::highlightParagraph(const TQString &text,int endStateOfLastPara)

{
	const TQChar * pBuf = (const TQChar *)text.ucs2();
	const TQChar * c = pBuf;
	if(!c)return endStateOfLastPara;
	
	if(endStateOfLastPara < 0)endStateOfLastPara = 0;
	
	bool bNewCommand = !(endStateOfLastPara & IN_LINE);
	bool bInComment = endStateOfLastPara & IN_COMMENT;
	bool bInString = endStateOfLastPara & IN_STRING;
	
	const TQChar * pBegin;


	while(c->unicode())
	{
		if(bInComment)
		{
			pBegin = c;
			while(c->unicode() && (c->unicode() != '*'))c++;
			if(!c->unicode())
			{
				setFormat(pBegin - pBuf,c - pBegin,g_fntNormal,g_clrComment);
				return IN_COMMENT;
			}
			c++;
			if(c->unicode() == '/')
			{
				// end of the comment!
				c++;
				setFormat(pBegin - pBuf,c - pBegin,g_fntNormal,g_clrComment);
				bInComment = false;
				bNewCommand = true;
			}
			continue;
		}

		if(c->isSpace())
		{
			while(c->unicode() && c->isSpace())c++;
			if(!c->unicode())continue;
		}

		pBegin = c;

		// this does not break the bNewCommand flag
		if((c->unicode() == '{') || (c->unicode() == '}'))
		{
			c++;
			setFormat(pBegin - pBuf,1,g_fntNormal,g_clrBracket);
			continue;
		}


		if(bNewCommand)
		{
			bNewCommand = false;

			if(c->unicode() == '#')
			{
				if(c > pBuf)
				{
					const TQChar * prev = c - 1;
					if((prev->unicode() == ']') || (prev->unicode() == '}'))
					{
						// array or hash count
						c++;
						setFormat(pBegin - pBuf,c - pBegin,g_fntNormal,g_clrPunctuation);
						continue;
					}
				}
				// comment until the end of the line
				while(c->unicode())c++;
				setFormat(pBegin - pBuf,c - pBegin,g_fntNormal,g_clrComment);
				continue;
			}
			if(c->unicode() == '/')
			{
				c++;
				if(c->unicode() == '/')
				{
					while(c->unicode())c++;
					setFormat(pBegin - pBuf,c - pBegin,g_fntNormal,g_clrComment);
					continue;
				} else if(c->unicode() == '*')
				{
					c++;
					setFormat(pBegin - pBuf,c - pBegin,g_fntNormal,g_clrComment);
					bInComment = true;
					continue;
				}
				c--;
			}
			if(c->unicode() && (c->isLetterOrNumber() || (c->unicode() == '_')))
			{
				c++;
				while(c->unicode() && (c->isLetterOrNumber() || (c->unicode() == '.') || (c->unicode() == '_') || (c->unicode() == ':')))c++;
				setFormat(pBegin - pBuf,c - pBegin,g_fntNormal,g_clrKeyword);
				// special processing for callbacks and magic commands
				if(pBegin->unicode() == 'e')
				{
					if(c - pBegin == 4)
					{
						// might be "else"
						TQString tmp(pBegin,4);
						if(tmp.lower() == "else")bNewCommand = true;
						continue;
					}
				}
				else
				if(pBegin->unicode() == 'f')
				{
					if(c - pBegin == 8)
					{
						// might be "function"
						TQString tmp(pBegin,8);
						if(tmp.lower() == "function")bNewCommand = true;
						continue;
					}
				}

				if(pBegin->unicode() == 'i')
				{
					if(c - pBegin == 8)
					{
						// might be "internal"
						TQString tmp(pBegin,8);
						if(tmp.lower() == "internal")bNewCommand = true;
						continue;
					}
				}

				// not an else or special command function... FIXME: should check for callbacks.. but that's prolly too difficult :)
				continue;
			}
		}
		if(c->unicode() == '$')
		{
			c++;
			if(c->unicode() == '$')
			{
				c++;
				setFormat(pBegin - pBuf,c - pBegin,g_fntNormal,g_clrKeyword);
			} else {
				while(c->unicode() && (c->isLetterOrNumber() || (c->unicode() == '.') || (c->unicode() == '_') || (c->unicode() == ':')))c++;
				setFormat(pBegin - pBuf,c - pBegin,g_fntNormal,g_clrFunction);
			}
			continue;
		}
		
		if(c->unicode() == '-')
		{
			TQChar * pTmp =(TQChar *) c;
			c++;
			if(c->unicode() == '-')	c++;
			if(c->isLetter())
			{
				while(c->unicode() && (c->isLetterOrNumber() || (c->unicode() == '_')))c++;
				setFormat(pBegin - pBuf,c - pBegin,g_fntNormal,g_clrKeyword);
				continue;
			} else {
				while(c!=pTmp) c--;
			}
		}

		if(c->unicode() == '%')
		{
			c++;
			if(c->unicode() && (c->isLetterOrNumber() || (c->unicode() == ':') || (c->unicode() == '_')))
			{
				while(c->unicode() && (c->isLetterOrNumber() || (c->unicode() == ':') || (c->unicode() == '_')))c++;
				setFormat(pBegin - pBuf,c - pBegin,g_fntNormal,g_clrVariable);
				continue;
			}
			c--;
		}

		if(!c->unicode())continue;

		if(c->isLetterOrNumber() || c->unicode() == '_')
		{
			c++;
			while(c->unicode() && c->isLetterOrNumber() || (c->unicode() == '_'))c++;
			setFormat(pBegin - pBuf,c - pBegin,g_fntNormal,g_clrNormalText);
			continue;
		}

		if(c->unicode() == '\\')
		{
			c++;
			setFormat(pBegin - pBuf,c - pBegin,g_fntNormal,g_clrPunctuation);
			// the next char is to be interpreted as normal text
			pBegin = c;
			if(c->unicode() && (c->unicode() != '\n'))
			{
				c++;
				setFormat(pBegin - pBuf,c - pBegin,g_fntNormal,g_clrNormalText);
				continue;
			}
			// this is never returned since TQt sux in string processing
			// it sets the newlines to spaces and we have no secure way to undestand that this was the end of a line
			return IN_LINE;
		}

		if(c->unicode() == '"')
		{
			bInString = !bInString;
			c++;
			setFormat(pBegin - pBuf,c - pBegin,g_fntNormal,g_clrPunctuation);
			continue;
		} else if(c->unicode() == ';')
		{
			if(!bInString)	bNewCommand = true; // the next will be a new command
		}

		c++;
		if(bInString)
		{
			setFormat(pBegin - pBuf,c - pBegin,g_fntNormal,g_clrNormalText);
		} else {
			setFormat(pBegin - pBuf,c - pBegin,g_fntNormal,g_clrPunctuation);
		}
	}

	bool i=TRUE;
	TQString szFind=((KviScriptEditorWidget *)textEdit())->m_szFind;
	if (!szFind.isEmpty())
	{
		int index=0;
		while (i)
		{
			index=text.find(szFind,index,false);
			if (index != -1)
			{
				setFormat(index,szFind.length(),g_clrFind);
				index += szFind.length();
			}
		else i=false;
		}
	}
	if(bInString)
		return IN_LINE | IN_STRING;
	else 
		return 0;
}

// 22.02.2005 :: 00:01
// valgrind --leak-check=yes --num-callers=10 -v kvirc -f
//
//==30299== Warning: SIGSEGV not in user code; either from syscall kill()
//==30299==    or possible Valgrind bug.  This message is only shown 3 times.
//==30299== Warning: SIGSEGV not in user code; either from syscall kill()
//==30299==    or possible Valgrind bug.  This message is only shown 3 times.
//==30299== Warning: SIGSEGV not in user code; either from syscall kill()
//==30299==    or possible Valgrind bug.  This message is only shown 3 times.


KviScriptEditorImplementation::KviScriptEditorImplementation(TQWidget * par)
:KviScriptEditor(par)
{
	if(g_pScriptEditorWindowList->isEmpty())loadOptions();
	g_pScriptEditorWindowList->append(this);
	m_lastCursorPos=TQPoint(0,0);
	TQGridLayout * g = new TQGridLayout(this,2,3,0,0);

	m_pFindLineedit = new TQLineEdit(" ",this);
#ifndef COMPILE_USE_QT4
	m_pFindLineedit->setFrameStyle(TQFrame::Sunken | TQFrame::Panel);
#endif
	m_pFindLineedit->setText("");
	m_pFindLineedit->setPaletteForegroundColor(g_clrFind);

	m_pEditor = new KviScriptEditorWidget(this);
	g->addMultiCellWidget(m_pEditor,0,0,0,3);
	g->setRowStretch(0,1);

#ifdef COMPILE_USE_QT4
	TQToolButton * b = new TQToolButton(TQt::DownArrow,this,"dsa2");
#else
	TQToolButton * b = new TQToolButton(DownArrow,this);
#endif
	b->setMinimumWidth(24);
	g->addWidget(b,1,0);

	KviTalPopupMenu * pop = new KviTalPopupMenu(b);
	pop->insertItem(__tr2qs_ctx("&Open...","editor"),this,TQT_SLOT(loadFromFile()));
	pop->insertItem(__tr2qs_ctx("&Save As...","editor"),this,TQT_SLOT(saveToFile()));
	pop->insertSeparator();
	pop->insertItem(__tr2qs_ctx("&Configure Editor...","editor"),this,TQT_SLOT(configureColors()));
	b->setPopup(pop);
	b->setPopupDelay(1);

	g->setColStretch(1,1);
	g->setColStretch(2,10);
	g->addWidget(m_pFindLineedit,1,2);
	TQLabel *lab= new TQLabel("find",this);
	lab->setText(tr("Find"));

	g->addWidget(lab,1,1);
	m_pRowColLabel = new TQLabel("0",this);
	m_pRowColLabel->setFrameStyle(TQFrame::Sunken | TQFrame::Panel);
	m_pRowColLabel->setMinimumWidth(80);
	g->addWidget(m_pRowColLabel,1,3);

	connect(m_pFindLineedit,TQT_SIGNAL(returnPressed()),m_pEditor,TQT_SLOT(slotFind()));
	connect(m_pFindLineedit,TQT_SIGNAL(returnPressed()),this,TQT_SLOT(slotFind()));
	connect(m_pEditor,TQT_SIGNAL(keyPressed()),this,TQT_SLOT(updateRowColLabel()));
	connect(m_pEditor,TQT_SIGNAL(textChanged()),this,TQT_SLOT(updateRowColLabel()));
	connect(m_pEditor,TQT_SIGNAL(selectionChanged()),this,TQT_SLOT(updateRowColLabel()));
	m_lastCursorPos = TQPoint(-1,-1);
}

KviScriptEditorImplementation::~KviScriptEditorImplementation()
{
	g_pScriptEditorWindowList->removeRef(this);
	if(g_pScriptEditorWindowList->isEmpty())saveOptions();
}

void KviScriptEditorImplementation::loadOptions()
{
	TQString tmp;
	g_pEditorModulePointer->getDefaultConfigFileName(tmp);

	KviConfig cfg(tmp,KviConfig::Read);
	
	g_clrBackground = cfg.readColorEntry("Background",TQColor(0,0,0));;
	g_clrNormalText = cfg.readColorEntry("NormalText",TQColor(100,255,0));
	g_clrBracket = cfg.readColorEntry("Bracket",TQColor(255,0,0));
	g_clrComment = cfg.readColorEntry("Comment",TQColor(0,120,0));
	g_clrFunction = cfg.readColorEntry("Function",TQColor(255,255,0));
	g_clrKeyword = cfg.readColorEntry("Keyword",TQColor(120,120,150));
	g_clrVariable = cfg.readColorEntry("Variable",TQColor(200,200,200));
	g_clrPunctuation = cfg.readColorEntry("Punctuation",TQColor(180,180,0));
	g_clrFind = cfg.readColorEntry("Find",TQColor(255,0,0));

	g_fntNormal = cfg.readFontEntry("Font",TQFont("Fixed",12));
}

bool KviScriptEditorImplementation::isModified()
{
	return m_pEditor->isModified();
}

void KviScriptEditorImplementation::slotFind()
{
	emit find(m_pFindLineedit->text());

}
void KviScriptEditorImplementation::slotNextFind(const TQString &text)
{
//	emit nextFind(const TQString &text);

}void KviScriptEditorImplementation::slotInitFind()
{
	emit initFind();

}
void KviScriptEditorImplementation::slotReplaceAll(const TQString &txt,const TQString &txt1)
{
	emit replaceAll(txt,txt1);
}
void KviScriptEditorImplementation::saveOptions()
{
	TQString tmp;
	g_pEditorModulePointer->getDefaultConfigFileName(tmp);

	KviConfig cfg(tmp,KviConfig::Write);
	
	cfg.writeEntry("Background",g_clrBackground);;
	cfg.writeEntry("NormalText",g_clrNormalText);
	cfg.writeEntry("Bracket",g_clrBracket);
	cfg.writeEntry("Comment",g_clrComment);
	cfg.writeEntry("Function",g_clrFunction);
	cfg.writeEntry("Keyword",g_clrKeyword);
	cfg.writeEntry("Variable",g_clrVariable);
	cfg.writeEntry("Punctuation",g_clrPunctuation);
	cfg.writeEntry("Find",g_clrFind);
	cfg.writeEntry("Font",g_fntNormal);
}

void KviScriptEditorImplementation::setFocus()
{
	m_pEditor->setFocus();
}



void KviScriptEditorImplementation::focusInEvent(TQFocusEvent *)
{
	m_pEditor->setFocus();
}


void KviScriptEditorImplementation::setEnabled(bool bEnabled)
{
	TQWidget::setEnabled(bEnabled);
	m_pEditor->setEnabled(bEnabled);
	m_pRowColLabel->setEnabled(bEnabled);
}

void KviScriptEditorImplementation::saveToFile()
{
	TQString fName;
	if(KviFileDialog::askForSaveFileName(fName,
		__tr2qs_ctx("Choose a Filename - KVIrc","editor"),
		TQString(),
		TQString(),false,true,true))
	{
		TQString buffer = m_pEditor->text();

		//if(tmp.isEmpty())tmp = "";
		//KviStr buffer = tmp.utf8().data();
		if(!KviFileUtils::writeFile(fName,buffer))
		{
			TQString tmp;
			TQMessageBox::warning(this,
				__tr2qs_ctx("Save Failed - KVIrc","editor"),
				KviTQString::sprintf(tmp,__tr2qs_ctx("Can't open the file %s for writing.","editor"),&fName));
		}
	}
}

void KviScriptEditorImplementation::setText(const KviTQCString &txt)
{
	m_pEditor->setText(txt.data());
#ifdef COMPILE_USE_QT4
	m_pEditor->setTextFormat(TQt::PlainText);
#else
	m_pEditor->setTextFormat(KviTalTextEdit::PlainText);
#endif
	m_pEditor->moveCursor(KviTalTextEdit::MoveEnd,false);
	m_pEditor->setModified(false);
	updateRowColLabel();
}

void KviScriptEditorImplementation::getText(KviTQCString &txt)
{
	txt = m_pEditor->text();
}
TQLineEdit * KviScriptEditorImplementation::getFindlineedit()
{
	return m_pFindLineedit;
}
void KviScriptEditorImplementation::setText(const TQString &txt)
{
	m_pEditor->setText(txt);
#ifdef COMPILE_USE_QT4
	m_pEditor->setTextFormat(TQt::PlainText);
#else
	m_pEditor->setTextFormat(KviTalTextEdit::PlainText);
#endif
	m_pEditor->moveCursor(KviTalTextEdit::MoveEnd,false);
	m_pEditor->setModified(false);
	updateRowColLabel();
}

void KviScriptEditorImplementation::getText(TQString &txt)
{
	txt = m_pEditor->text();
}
void KviScriptEditorImplementation::setFindText(const TQString &txt)
{
	m_pFindLineedit->setText(txt);
	m_pEditor->slotFind();

}

void KviScriptEditorImplementation::setFindLineeditReadOnly(bool b)
{
	m_pFindLineedit->setReadOnly(b);
	
}


void KviScriptEditorImplementation::updateRowColLabel()
{
	int iRow,iCol;
	m_pEditor->getCursorPosition(&iRow,&iCol);
	if(iRow != m_lastCursorPos.x() || iCol != m_lastCursorPos.y())
	{
		m_lastCursorPos = TQPoint(iRow,iCol);
		TQString tmp;
		KviTQString::sprintf(tmp,__tr2qs_ctx("Row: %d Col: %d","editor"),iRow,iCol);
		m_pRowColLabel->setText(tmp);
	}
}

TQPoint KviScriptEditorImplementation::getCursor()
{
		return m_lastCursorPos;
}
void KviScriptEditorImplementation::setCursorPosition(TQPoint pos)
{
	m_pEditor->setCursorPosition(pos.x(),pos.y());
	m_pEditor->setFocus();
	m_pEditor->ensureCursorVisible();
	TQString tmp;
	KviTQString::sprintf(tmp,__tr2qs_ctx("Row: %d Col: %d","editor"),pos.x(),pos.y());
	m_pRowColLabel->setText(tmp);
	
	m_lastCursorPos=pos;
}

void KviScriptEditorImplementation::loadFromFile()
{
	TQString fName;
	if(KviFileDialog::askForOpenFileName(fName,
		__tr2qs_ctx("Load Script File - KVIrc","editor"),
		TQString(),
		TQString(),false,true))
	{
		TQString buffer;
		if(KviFileUtils::loadFile(fName,buffer))
		{
			m_pEditor->setText(buffer);
			m_pEditor->moveCursor(KviTalTextEdit::MoveEnd,false);
			updateRowColLabel();
		} else {
			TQString tmp;
			TQMessageBox::warning(this,
				__tr2qs_ctx("Open Failed - KVIrc","editor"),
				KviTQString::sprintf(tmp,__tr2qs_ctx("Can't open the file %s for reading.","editor"),&fName));
		}
	}
}

void KviScriptEditorImplementation::configureColors()
{
	KviScriptEditorWidgetColorOptions dlg(this);
	if(dlg.exec() == TQDialog::Accepted)

	{
		m_pEditor->updateOptions();
		saveOptions();
	}
}
KviScriptEditorReplaceDialog::KviScriptEditorReplaceDialog( TQWidget* parent, const char* name)
    : TQDialog( parent)
{
	m_pParent=parent;
	emit initFind();
	setPaletteForegroundColor( TQColor( 0, 0, 0 ) );
	setPaletteBackgroundColor( TQColor( 236, 233, 216 ) );
	TQGridLayout *layout = new TQGridLayout( this, 1, 1, 11, 6, "replace layout"); 
 
	m_pFindlineedit = new TQLineEdit( this, "findlineedit" );
#ifndef COMPILE_USE_QT4
	m_pFindlineedit->setSizePolicy( TQSizePolicy( (TQSizePolicy::SizeType)7, (TQSizePolicy::SizeType)0, 0, 0, m_pFindlineedit->sizePolicy().hasHeightForWidth() ) );
	m_pFindlineedit->setFrameShape( TQLineEdit::LineEditPanel );
	m_pFindlineedit->setFrameShadow( TQLineEdit::Sunken );
#endif

	layout->addMultiCellWidget( m_pFindlineedit, 2, 2, 1, 2 );

	m_pReplacelineedit = new TQLineEdit( this, "replacelineedit" );
#ifndef COMPILE_USE_QT4
	m_pReplacelineedit->setFrameShape( TQLineEdit::LineEditPanel );
	m_pReplacelineedit->setFrameShadow( TQLineEdit::Sunken );
#endif
	layout->addMultiCellWidget( m_pReplacelineedit, 3, 3, 1, 2 );

   	m_pFindlineedit->setFocus();

    TQLabel *findlabel = new TQLabel( this, "findlabel" );
	findlabel->setText(tr("Word to Find"));
#ifndef COMPILE_USE_QT4
	findlabel->setAutoResize(true);
#endif

	layout->addWidget( findlabel, 2, 0 );

    TQLabel *replacelabel = new TQLabel( this, "replacelabel" );
	replacelabel->setText(tr("Replace with"));
#ifndef COMPILE_USE_QT4
	replacelabel->setAutoResize(true);
#endif
	layout->addWidget( replacelabel, 3, 0 );

    TQPushButton *cancelbutton = new TQPushButton( this, "cancelButton" );
	cancelbutton->setText(tr("&Cancel"));
	layout->addWidget( cancelbutton, 5, 2 );

    replacebutton = new TQPushButton( this, "replacebutton" );
	replacebutton->setText(tr("&Replace"));
	replacebutton->setEnabled( FALSE );
	layout->addWidget( replacebutton, 5, 0 );

	checkReplaceAll = new KviStyledCheckBox( this, "replaceAll" );
	checkReplaceAll->setText(tr("&Replace in all Aliases"));
	layout->addWidget( checkReplaceAll, 4, 0 );
	
	findNext = new TQPushButton(this, "findNext(WIP)" );	
	findNext->setText(tr("&Findnext"));
	layout->addWidget( findNext, 2, 3 );
	findNext->setEnabled(false);

	replace = new TQPushButton(this, "replace" );	
	replace->setText(tr("&Replace(WIP)"));
	layout->addWidget( replace, 3, 3 );
	replace->setEnabled(false);

#ifndef COMPILE_USE_QT4
    clearWState( WState_Polished );
	setTabOrder(m_pFindlineedit,m_pReplacelineedit);
#endif
	// signals and slots connections
	connect( replacebutton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotReplace() ) );
	connect( findNext, TQT_SIGNAL( clicked() ),this,TQT_SLOT( slotNextFind()));
	connect( cancelbutton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( reject() ) );
	connect( m_pFindlineedit, TQT_SIGNAL( textChanged(const TQString &)), this, TQT_SLOT( textChanged(const TQString &)));

}


KviScriptEditorReplaceDialog::~KviScriptEditorReplaceDialog()
{
}

void KviScriptEditorReplaceDialog::textChanged(const TQString &txt)
{
	if (!txt.isEmpty()) replacebutton->setEnabled(TRUE);
	else replacebutton->setEnabled(FALSE);

}
void KviScriptEditorReplaceDialog::slotReplace()
{
	TQString txt=((KviScriptEditorWidget *)m_pParent)->text();
	if (checkReplaceAll->isChecked()) emit replaceAll(m_pFindlineedit->text(),m_pReplacelineedit->text());
	txt.replace(m_pFindlineedit->text(),m_pReplacelineedit->text(),false);
	((KviScriptEditorWidget *)m_pParent)->setText(txt);
	((KviScriptEditorWidget *)m_pParent)->setModified(true);
	m_pFindlineedit->setText("");
	m_pReplacelineedit->setText("");
	setTabOrder(m_pFindlineedit,m_pReplacelineedit);
}


void KviScriptEditorReplaceDialog::slotNextFind()
{
	emit nextFind(m_pFindlineedit->text());
}