summaryrefslogtreecommitdiffstats
path: root/kmail/kmedit.cpp
blob: bb1bb88f67f50e6687da10a754ad815293d13117 (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
// -*- mode: C++; c-file-style: "gnu" -*-
// kmcomposewin.cpp
// Author: Markus Wuebben <markus.wuebben@kde.org>
// This code is published under the GPL.

#include <config.h>

#include "kmedit.h"
#include "kmlineeditspell.h"

#define REALLY_WANT_KMCOMPOSEWIN_H
#include "kmcomposewin.h"
#undef REALLY_WANT_KMCOMPOSEWIN_H
#include "kmmsgdict.h"
#include "kmfolder.h"
#include "kmcommands.h"

#include <maillistdrag.h>
using KPIM::MailListDrag;

#include <libkdepim/kfileio.h>
#include <libemailfunctions/email.h>

#include <kcursor.h>
#include <kprocess.h>

#include <kpopupmenu.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kurldrag.h>

#include <ktempfile.h>
#include <klocale.h>
#include <kapplication.h>
#include <kdirwatch.h>
#include <kiconloader.h>

#include "globalsettings.h"
#include "replyphrases.h"

#include <kspell.h>
#include <kspelldlg.h>
#include <spellingfilter.h>
#include <ksyntaxhighlighter.h>

#include <tqregexp.h>
#include <tqbuffer.h>
#include <tqevent.h>

#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <assert.h>


void KMEdit::contentsDragEnterEvent(TQDragEnterEvent *e)
{
    if (e->provides(MailListDrag::format()))
        e->accept(true);
    else if (e->provides("image/png"))
        e->accept();
    else
        return KEdit::contentsDragEnterEvent(e);
}

void KMEdit::contentsDragMoveEvent(TQDragMoveEvent *e)
{
    if (e->provides(MailListDrag::format()))
        e->accept();
    else if (e->provides("image/png"))
        e->accept();
    else
        return KEdit::contentsDragMoveEvent(e);
}

void KMEdit::keyPressEvent( TQKeyEvent* e )
{
    if( e->key() == Key_Return ) {
        int line, col;
        getCursorPosition( &line, &col );
        TQString lineText = text( line );
        // returns line with additional trailing space (bug in Qt?), cut it off
        lineText.truncate( lineText.length() - 1 );
        // special treatment of quoted lines only if the cursor is neither at
        // the begin nor at the end of the line
        if( ( col > 0 ) && ( col < int( lineText.length() ) ) ) {
            bool isQuotedLine = false;
            uint bot = 0; // bot = begin of text after quote indicators
            while( bot < lineText.length() ) {
                if( ( lineText[bot] == '>' ) || ( lineText[bot] == '|' ) ) {
                    isQuotedLine = true;
                    ++bot;
                }
                else if( lineText[bot].isSpace() ) {
                    ++bot;
                }
                else {
                    break;
                }
            }

            KEdit::keyPressEvent( e );

            // duplicate quote indicators of the previous line before the new
            // line if the line actually contained text (apart from the quote
            // indicators) and the cursor is behind the quote indicators
            if( isQuotedLine
                && ( bot != lineText.length() )
                && ( col >= int( bot ) ) ) {

		// The cursor position might have changed unpredictably if there was selected
		// text which got replaced by a new line, so we query it again:
		getCursorPosition( &line, &col );
                TQString newLine = text( line );
                // remove leading white space from the new line and instead
                // add the quote indicators of the previous line
                unsigned int leadingWhiteSpaceCount = 0;
                while( ( leadingWhiteSpaceCount < newLine.length() )
                       && newLine[leadingWhiteSpaceCount].isSpace() ) {
                    ++leadingWhiteSpaceCount;
                }
                newLine = newLine.replace( 0, leadingWhiteSpaceCount,
                                           lineText.left( bot ) );
                removeParagraph( line );
                insertParagraph( newLine, line );
                // place the cursor at the begin of the new line since
                // we assume that the user split the quoted line in order
                // to add a comment to the first part of the quoted line
                setCursorPosition( line, 0 );
            }
        }
        else
            KEdit::keyPressEvent( e );
    }
    else
        KEdit::keyPressEvent( e );
}

void KMEdit::contentsDropEvent(TQDropEvent *e)
{
    if (e->provides(MailListDrag::format())) {
        // Decode the list of serial numbers stored as the drag data
        TQByteArray serNums;
        MailListDrag::decode( e, serNums );
        TQBuffer serNumBuffer(serNums);
        serNumBuffer.open(IO_ReadOnly);
        TQDataStream serNumStream(&serNumBuffer);
        Q_UINT32 serNum;
        KMFolder *folder = 0;
        int idx;
        TQPtrList<KMMsgBase> messageList;
        while (!serNumStream.atEnd()) {
            KMMsgBase *msgBase = 0;
            serNumStream >> serNum;
            KMMsgDict::instance()->getLocation(serNum, &folder, &idx);
            if (folder)
                msgBase = folder->getMsgBase(idx);
            if (msgBase)
                messageList.append( msgBase );
        }
        serNumBuffer.close();
        uint identity = folder ? folder->identity() : 0;
        KMCommand *command =
            new KMForwardAttachedCommand(mComposer, messageList,
                                         identity, mComposer);
        command->start();
    }
    else if( e->provides("image/png") ) {
        emit attachPNGImageData(e->encodedData("image/png"));
    }
    else if( KURLDrag::canDecode( e ) ) {
        KURL::List urlList;
        if( KURLDrag::decode( e, urlList ) ) {
            KPopupMenu p;
            p.insertItem( i18n("Add as Text"), 0 );
            p.insertItem( i18n("Add as Attachment"), 1 );
            int id = p.exec( mapToGlobal( e->pos() ) );
            switch ( id) {
              case 0:
                for ( KURL::List::Iterator it = urlList.begin();
                     it != urlList.end(); ++it ) {
                  insert( (*it).url() );
                }
                break;
              case 1:
                for ( KURL::List::Iterator it = urlList.begin();
                     it != urlList.end(); ++it ) {
                  mComposer->addAttach( *it );
                }
                break;
            }
        }
        else if ( TQTextDrag::canDecode( e ) ) {
          TQString s;
          if ( TQTextDrag::decode( e, s ) )
            insert( s );
        }
        else
          kdDebug(5006) << "KMEdit::contentsDropEvent, unable to add dropped object" << endl;
    } 
    else if( e->provides("text/x-textsnippet") ) {
	emit insertSnippet();
    } 
    else {
        KEdit::contentsDropEvent(e);
    }
}

KMEdit::KMEdit(TQWidget *parent, KMComposeWin* composer,
               KSpellConfig* autoSpellConfig,
               const char *name)
  : KEdit( parent, name ),
    mComposer( composer ),
    mKSpell( 0 ),
    mSpellConfig( autoSpellConfig ),
    mSpellingFilter( 0 ),
    mExtEditorTempFile( 0 ),
    mExtEditorTempFileWatcher( 0 ),
    mExtEditorProcess( 0 ),
    mUseExtEditor( false ),
    mWasModifiedBeforeSpellCheck( false ),
    mSpellChecker( 0 ),
    mSpellLineEdit( false ),
    mPasteMode( QClipboard::Clipboard )
{
  installEventFilter(this);
  KCursor::setAutoHideCursor( this, true, true );
  setOverwriteEnabled( true );
}


void KMEdit::initializeAutoSpellChecking()
{
  if ( mSpellChecker )
    return; // already initialized
  TQColor defaultColor1( 0x00, 0x80, 0x00 ); // defaults from kmreaderwin.cpp
  TQColor defaultColor2( 0x00, 0x70, 0x00 );
  TQColor defaultColor3( 0x00, 0x60, 0x00 );
  TQColor defaultForeground( kapp->palette().active().text() );

  TQColor c = Qt::red;
  KConfigGroup readerConfig( KMKernel::config(), "Reader" );
  TQColor col1;
  if ( !readerConfig.readBoolEntry(  "defaultColors", true ) )
      col1 = readerConfig.readColorEntry( "ForegroundColor", &defaultForeground );
  else
      col1 = defaultForeground;
  TQColor col2 = readerConfig.readColorEntry( "QuotedText3", &defaultColor3 );
  TQColor col3 = readerConfig.readColorEntry( "QuotedText2", &defaultColor2 );
  TQColor col4 = readerConfig.readColorEntry( "QuotedText1", &defaultColor1 );
  TQColor misspelled = readerConfig.readColorEntry( "MisspelledColor", &c );
  mSpellChecker = new KDictSpellingHighlighter( this, /*active*/ true,
                                                /*autoEnabled*/ false,
                                                /*spellColor*/ misspelled,
                                                /*colorQuoting*/ true,
                                                col1, col2, col3, col4,
                                                mSpellConfig );

  connect( mSpellChecker, TQT_SIGNAL(newSuggestions(const TQString&, const TQStringList&, unsigned int)),
           this, TQT_SLOT(addSuggestion(const TQString&, const TQStringList&, unsigned int)) );
}


TQPopupMenu *KMEdit::createPopupMenu( const TQPoint& pos )
{
  enum { IdUndo, IdRedo, IdSep1, IdCut, IdCopy, IdPaste, IdClear, IdSep2, IdSelectAll };

  TQPopupMenu *menu = KEdit::createPopupMenu( pos );
  if ( !TQApplication::clipboard()->image().isNull() ) {
    int id = menu->idAt(0);
    menu->setItemEnabled( id - IdPaste, true);
  }

  return menu;
}

void KMEdit::deleteAutoSpellChecking()
{ // because the highlighter doesn't support RichText, delete its instance.
  delete mSpellChecker;
  mSpellChecker =0;
}

void KMEdit::addSuggestion(const TQString& text, const TQStringList& lst, unsigned int )
{
  mReplacements[text] = lst;
}

void KMEdit::setSpellCheckingActive(bool spellCheckingActive)
{
  if ( mSpellChecker ) {
    mSpellChecker->setActive(spellCheckingActive);
  }
}


KMEdit::~KMEdit()
{
  removeEventFilter(this);

  delete mKSpell;
  delete mSpellChecker;
  mSpellChecker = 0;

}



TQString KMEdit::brokenText()
{
  TQString temp, line;

  int num_lines = numLines();
  for (int i = 0; i < num_lines; ++i)
  {
    int lastLine = 0;
    line = textLine(i);
    for (int j = 0; j < (int)line.length(); ++j)
    {
      if (lineOfChar(i, j) > lastLine)
      {
        lastLine = lineOfChar(i, j);
        temp += '\n';
      }
      temp += line[j];
    }
    if (i + 1 < num_lines) temp += '\n';
  }

  return temp;
}


unsigned int KMEdit::lineBreakColumn() const
{
  unsigned int lineBreakColumn = 0;
  unsigned int numlines = numLines();
  while ( numlines-- ) {
    lineBreakColumn = QMAX( lineBreakColumn, textLine( numlines ).length() );
  }
  return lineBreakColumn;
}


bool KMEdit::eventFilter(TQObject*o, TQEvent* e)
{
  if (o == this)
    KCursor::autoHideEventFilter(o, e);

  if (e->type() == TQEvent::KeyPress)
  {
    TQKeyEvent *k = (TQKeyEvent*)e;

    if (mUseExtEditor) {
      if (k->key() == Key_Up)
      {
        emit focusUp();
        return true;
      }

      // ignore modifier keys (cf. bug 48841)
      if ( (k->key() == Key_Shift) || (k->key() == Key_Control) ||
           (k->key() == Key_Meta) || (k->key() == Key_Alt) )
        return true;
      if (mExtEditorTempFile) return true;
      TQString sysLine = mExtEditor;
      mExtEditorTempFile = new KTempFile();

      mExtEditorTempFile->setAutoDelete(true);

      (*mExtEditorTempFile->textStream()) << text();

      mExtEditorTempFile->close();
      // replace %f in the system line
      sysLine.replace( "%f", mExtEditorTempFile->name() );
      mExtEditorProcess = new KProcess();
      mExtEditorProcess->setUseShell( true );
      sysLine += " ";
      while (!sysLine.isEmpty())
      {
        *mExtEditorProcess << sysLine.left(sysLine.find(" ")).local8Bit();
        sysLine.remove(0, sysLine.find(" ") + 1);
      }
      connect(mExtEditorProcess, TQT_SIGNAL(processExited(KProcess*)),
              TQT_SLOT(slotExternalEditorDone(KProcess*)));
      if (!mExtEditorProcess->start())
      {
        KMessageBox::error( topLevelWidget(),
                            i18n("Unable to start external editor.") );
        killExternalEditor();
      } else {
        mExtEditorTempFileWatcher = new KDirWatch( this, "mExtEditorTempFileWatcher" );
        connect( mExtEditorTempFileWatcher, TQT_SIGNAL(dirty(const TQString&)),
                 TQT_SLOT(slotExternalEditorTempFileChanged(const TQString&)) );
        mExtEditorTempFileWatcher->addFile( mExtEditorTempFile->name() );
      }
      return true;
    } else {
    // ---sven's Arrow key navigation start ---
    // Key Up in first line takes you to Subject line.
    if (k->key() == Key_Up && k->state() != ShiftButton && currentLine() == 0
      && lineOfChar(0, currentColumn()) == 0)
    {
      deselect();
      emit focusUp();
      return true;
    }
    // ---sven's Arrow key navigation end ---

    if (k->key() == Key_Backtab && k->state() == ShiftButton)
    {
      deselect();
      emit focusUp();
      return true;
    }

    }
  } else if ( e->type() == TQEvent::ContextMenu ) {
    TQContextMenuEvent *event = (TQContextMenuEvent*) e;

    int para = 1, charPos, firstSpace, lastSpace;

    //Get the character at the position of the click
    charPos = charAt( viewportToContents(event->pos()), &para );
    TQString paraText = text( para );

    if( !paraText.at(charPos).isSpace() )
    {
      //Get word right clicked on
      const TQRegExp wordBoundary( "[\\s\\W]" );
      firstSpace = paraText.findRev( wordBoundary, charPos ) + 1;
      lastSpace = paraText.find( wordBoundary, charPos );
      if( lastSpace == -1 )
        lastSpace = paraText.length();
      TQString word = paraText.mid( firstSpace, lastSpace - firstSpace );
      //Continue if this word was misspelled
      if( !word.isEmpty() && mReplacements.contains( word ) )
      {
        KPopupMenu p;
        p.insertTitle( i18n("Suggestions") );

        //Add the suggestions to the popup menu
        TQStringList reps = mReplacements[word];
        if( reps.count() > 0 )
        {
          int listPos = 0;
          for ( TQStringList::Iterator it = reps.begin(); it != reps.end(); ++it ) {
            p.insertItem( *it, listPos );
            listPos++;
          }
        }
        else
        {
          p.insertItem( TQString::fromLatin1("No Suggestions"), -2 );
        }

        //Execute the popup inline
        int id = p.exec( mapToGlobal( event->pos() ) );

        if( id > -1 )
        {
          //Save the cursor position
          int parIdx = 1, txtIdx = 1;
          getCursorPosition(&parIdx, &txtIdx);
          setSelection(para, firstSpace, para, lastSpace);
          insert(mReplacements[word][id]);
          // Restore the cursor position; if the cursor was behind the
          // misspelled word then adjust the cursor position
          if ( para == parIdx && txtIdx >= lastSpace )
            txtIdx += mReplacements[word][id].length() - word.length();
          setCursorPosition(parIdx, txtIdx);
        }
        //Cancel original event
        return true;
      }
    }
  } else if ( e->type() == TQEvent::FocusIn || e->type() == TQEvent::FocusOut ) {
    TQFocusEvent *fe = static_cast<TQFocusEvent*>(e);
    if(! (fe->reason() == TQFocusEvent::ActiveWindow || fe->reason() == TQFocusEvent::Popup) )
      emit focusChanged( fe->gotFocus() );
  }

  return KEdit::eventFilter(o, e);
}


int KMEdit::autoSpellChecking( bool on )
{
  if ( textFormat() == Qt::RichText ) {
     // syntax highlighter doesn't support extended text properties
     if ( on )
       KMessageBox::sorry(this, i18n("Automatic spellchecking is not possible on text with markup."));
     return -1;
  }
  if ( mSpellChecker ) {
    // don't autoEnable spell checking if the user turned spell checking off
    mSpellChecker->setAutomatic( on );
    mSpellChecker->setActive( on );
  }
  return 1;
}


void KMEdit::slotExternalEditorTempFileChanged( const TQString & fileName ) {
  if ( !mExtEditorTempFile )
    return;
  if ( fileName != mExtEditorTempFile->name() )
    return;
  // read data back in from file
  setAutoUpdate(false);
  clear();

  insertLine(TQString::fromLocal8Bit(KPIM::kFileToString( fileName, true, false )), -1);
  setAutoUpdate(true);
  repaint();
}

void KMEdit::slotExternalEditorDone( KProcess * proc ) {
  assert(proc == mExtEditorProcess);
  // make sure, we update even when KDirWatcher is too slow:
  slotExternalEditorTempFileChanged( mExtEditorTempFile->name() );
  killExternalEditor();
}

void KMEdit::killExternalEditor() {
  delete mExtEditorTempFileWatcher; mExtEditorTempFileWatcher = 0;
  delete mExtEditorTempFile; mExtEditorTempFile = 0;
  delete mExtEditorProcess; mExtEditorProcess = 0;
}


bool KMEdit::checkExternalEditorFinished() {
  if ( !mExtEditorProcess )
    return true;
  switch ( KMessageBox::warningYesNoCancel( topLevelWidget(),
           i18n("The external editor is still running.\n"
                "Abort the external editor or leave it open?"),
           i18n("External Editor"),
           i18n("Abort Editor"), i18n("Leave Editor Open") ) ) {
  case KMessageBox::Yes:
    killExternalEditor();
    return true;
  case KMessageBox::No:
    return true;
  default:
    return false;
  }
}

void KMEdit::spellcheck()
{
  if ( mKSpell )
    return;
  mWasModifiedBeforeSpellCheck = isModified();
  mSpellLineEdit = !mSpellLineEdit;
//  maybe for later, for now plaintext is given to KSpell
//  if (textFormat() == Qt::RichText ) {
//    kdDebug(5006) << "KMEdit::spellcheck, spellchecking for RichText" << endl;
//    mKSpell = new KSpell(this, i18n("Spellcheck - KMail"), this,
//                    TQT_SLOT(slotSpellcheck2(KSpell*)),0,true,false,KSpell::HTML);
//  }
//  else {
    mKSpell = new KSpell(this, i18n("Spellcheck - KMail"), this,
                      TQT_SLOT(slotSpellcheck2(KSpell*)));
//  }

  TQStringList l = KSpellingHighlighter::personalWords();
  for ( TQStringList::Iterator it = l.begin(); it != l.end(); ++it ) {
      mKSpell->addPersonal( *it );
  }
  connect (mKSpell, TQT_SIGNAL( death()),
          this, TQT_SLOT (slotSpellDone()));
  connect (mKSpell, TQT_SIGNAL (misspelling (const TQString &, const TQStringList &, unsigned int)),
          this, TQT_SLOT (slotMisspelling (const TQString &, const TQStringList &, unsigned int)));
  connect (mKSpell, TQT_SIGNAL (corrected (const TQString &, const TQString &, unsigned int)),
          this, TQT_SLOT (slotCorrected (const TQString &, const TQString &, unsigned int)));
  connect (mKSpell, TQT_SIGNAL (done(const TQString &)),
          this, TQT_SLOT (slotSpellResult (const TQString&)));
}

void KMEdit::cut()
{
  KEdit::cut();
  if ( textFormat() != Qt::RichText && mSpellChecker )
    mSpellChecker->restartBackgroundSpellCheck();
}

void KMEdit::clear()
{
  KEdit::clear();
  if ( textFormat() != Qt::RichText && mSpellChecker )
    mSpellChecker->restartBackgroundSpellCheck();
}

void KMEdit::del()
{
  KEdit::del();
  if ( textFormat() != Qt::RichText && mSpellChecker )
    mSpellChecker->restartBackgroundSpellCheck();
}

void KMEdit::paste()
{
  mComposer->paste( mPasteMode );
}

// KMEdit indirectly inherits from TQTextEdit, which has virtual paste() method,
// but it controls whether it pastes clipboard or selection by an internal
// flag that is not accessible in any way, so paste() being virtual is actually
// useless, because reimplementations can't known where to paste from anyway.
// Roll our own internal flag.
void KMEdit::contentsMouseReleaseEvent( TQMouseEvent * e )
{
  if( e->button() != Qt::MidButton )
    return KEdit::contentsMouseReleaseEvent( e );
  mPasteMode = QClipboard::Selection;
  KEdit::contentsMouseReleaseEvent( e );
  mPasteMode = QClipboard::Clipboard;
}

void KMEdit::slotMisspelling(const TQString &text, const TQStringList &lst, unsigned int pos)
{
    kdDebug(5006)<<"void KMEdit::slotMisspelling(const TQString &text, const TQStringList &lst, unsigned int pos) : "<<text <<endl;
    if( mSpellLineEdit )
        mComposer->sujectLineWidget()->spellCheckerMisspelling( text, lst, pos);
    else
        misspelling(text, lst, pos);
}

void KMEdit::slotCorrected (const TQString &oldWord, const TQString &newWord, unsigned int pos)
{
    kdDebug(5006)<<"slotCorrected (const TQString &oldWord, const TQString &newWord, unsigned int pos) : "<<oldWord<<endl;
    if( mSpellLineEdit )
        mComposer->sujectLineWidget()->spellCheckerCorrected( oldWord, newWord, pos);
    else {
        unsigned int l = 0;
        unsigned int cnt = 0;
        bool _bold,_underline,_italic;
        TQColor _color;
        TQFont _font;
        posToRowCol (pos, l, cnt);
        setCursorPosition(l, cnt+1); // the new word will get the same markup now as the first character of the word
        _bold = bold();
        _underline = underline();
        _italic = italic();
        _color = color();
        _font = currentFont();
        corrected(oldWord, newWord, pos);
        setSelection (l, cnt, l, cnt+newWord.length());
        setBold(_bold);
        setItalic(_italic);
        setUnderline(_underline);
        setColor(_color);
        setCurrentFont(_font);
    }

}

void KMEdit::slotSpellcheck2(KSpell*)
{
    if( !mSpellLineEdit)
    {
        spellcheck_start();

        TQString quotePrefix;
        if(mComposer && mComposer->msg())
        {
            int languageNr = GlobalSettings::self()->replyCurrentLanguage();
            ReplyPhrases replyPhrases( TQString::number(languageNr) );
            replyPhrases.readConfig();

            quotePrefix = mComposer->msg()->formatString(
                 replyPhrases.indentPrefix() );
        }

        kdDebug(5006) << "spelling: new SpellingFilter with prefix=\"" << quotePrefix << "\"" << endl;
        TQTextEdit plaintext;
        plaintext.setText(text());
        plaintext.setTextFormat(Qt::PlainText);
        mSpellingFilter = new SpellingFilter(plaintext.text(), quotePrefix, SpellingFilter::FilterUrls,
                                             SpellingFilter::FilterEmailAddresses);

        mKSpell->check(mSpellingFilter->filteredText());
    }
    else if( mComposer )
        mKSpell->check( mComposer->sujectLineWidget()->text());
}

void KMEdit::slotSpellResult(const TQString &s)
{
    if( !mSpellLineEdit)
        spellcheck_stop();

  int dlgResult = mKSpell->dlgResult();
  if ( dlgResult == KS_CANCEL )
  {
      if( mSpellLineEdit)
      {
          //stop spell check
          mSpellLineEdit = false;
          TQString tmpText( s );
          tmpText =  tmpText.remove('\n');

          if( tmpText != mComposer->sujectLineWidget()->text() )
              mComposer->sujectLineWidget()->setText( tmpText );
      }
      else
      {
          setModified(true);
      }
  }
  mKSpell->cleanUp();
  KDictSpellingHighlighter::dictionaryChanged();

  emit spellcheck_done( dlgResult );
}

void KMEdit::slotSpellDone()
{
  kdDebug(5006)<<" void KMEdit::slotSpellDone()\n";
  KSpell::spellStatus status = mKSpell->status();
  delete mKSpell;
  mKSpell = 0;

  kdDebug(5006) << "spelling: delete SpellingFilter" << endl;
  delete mSpellingFilter;
  mSpellingFilter = 0;
  mComposer->sujectLineWidget()->deselect();
  if (status == KSpell::Error)
  {
     KMessageBox::sorry( topLevelWidget(),
                         i18n("ISpell/Aspell could not be started. Please "
                              "make sure you have ISpell or Aspell properly "
                              "configured and in your PATH.") );
     emit spellcheck_done( KS_CANCEL );
  }
  else if (status == KSpell::Crashed)
  {
     spellcheck_stop();
     KMessageBox::sorry( topLevelWidget(),
                         i18n("ISpell/Aspell seems to have crashed.") );
     emit spellcheck_done( KS_CANCEL );
  }
  else
  {
      if( mSpellLineEdit )
          spellcheck();
      else if( !mComposer->subjectTextWasSpellChecked() && status == KSpell::FinishedNoMisspellingsEncountered )
          KMessageBox::information( topLevelWidget(),
                                    i18n("No misspellings encountered.") );
  }
}

void KMEdit::setCursorPositionFromStart( unsigned int pos ) {
  unsigned int l = 0;
  unsigned int c = 0;
  posToRowCol( pos, l, c );
  // kdDebug() << "Num lines: " << numLines() << endl;
  // kdDebug() << "Position " << pos << " converted to " << l << ":" << c << endl;
  setCursorPosition( l, c );
  ensureCursorVisible();
}

#include "kmedit.moc"