summaryrefslogtreecommitdiffstats
path: root/kate/plugins/wordcompletion/docwordcompletion.cpp
blob: 37da55224a10a6a266209d6722ce999973b644c3 (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
/*
    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 Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

    ---
    file: docwordcompletion.cpp

    KTextEditor plugin to autocompletion with document words.
    Copyright Anders Lund <anders.lund@lund.tdcadsl.dk>, 2003

    The following completion methods are supported:
    * Completion with bigger matching words in
      either direction (backward/forward).
    * NOT YET Pop up a list of all bigger matching words in document

*/
//BEGIN includes
#include "docwordcompletion.h"

#include <ktexteditor/document.h>
#include <ktexteditor/viewcursorinterface.h>
#include <ktexteditor/editinterface.h>
#include <ktexteditor/variableinterface.h>

#include <kapplication.h>
#include <kconfig.h>
#include <kdialog.h>
#include <kgenericfactory.h>
#include <klocale.h>
#include <kaction.h>
#include <knotifyclient.h>
#include <kparts/part.h>
#include <kiconloader.h>

#include <tqregexp.h>
#include <tqstring.h>
#include <tqdict.h>
#include <tqspinbox.h>
#include <tqlabel.h>
#include <tqlayout.h>
#include <tqhbox.h>
#include <tqwhatsthis.h>
#include <tqcheckbox.h>

// #include <kdebug.h>
//END

//BEGIN DocWordCompletionPlugin
K_EXPORT_COMPONENT_FACTORY( ktexteditor_docwordcompletion, KGenericFactory<DocWordCompletionPlugin>( "ktexteditor_docwordcompletion" ) )
DocWordCompletionPlugin::DocWordCompletionPlugin( TQObject *parent,
                            const char* name,
                            const TQStringList& /*args*/ )
	: KTextEditor::Plugin ( (KTextEditor::Document*) parent, name )
{
  readConfig();
}

void DocWordCompletionPlugin::readConfig()
{
  KConfig *config = kapp->config();
  config->setGroup( "DocWordCompletion Plugin" );
  m_treshold = config->readNumEntry( "treshold", 3 );
  m_autopopup = config->readBoolEntry( "autopopup", true );
}

void DocWordCompletionPlugin::writeConfig()
{
  KConfig *config = kapp->config();
  config->setGroup("DocWordCompletion Plugin");
  config->writeEntry("autopopup", m_autopopup );
  config->writeEntry("treshold", m_treshold );
}

void DocWordCompletionPlugin::addView(KTextEditor::View *view)
{
  DocWordCompletionPluginView *nview = new DocWordCompletionPluginView (m_treshold, m_autopopup, view, "Document word completion");
  m_views.append (nview);
}

void DocWordCompletionPlugin::removeView(KTextEditor::View *view)
{
  for (uint z=0; z < m_views.count(); z++)
    if (m_views.at(z)->parentClient() == view)
    {
       DocWordCompletionPluginView *nview = m_views.at(z);
       m_views.remove (nview);
       delete nview;
    }
}

KTextEditor::ConfigPage* DocWordCompletionPlugin::configPage( uint, TQWidget *parent, const char *name )
{
  return new DocWordCompletionConfigPage( this, parent, name );
}

TQString DocWordCompletionPlugin::configPageName( uint ) const
{
  return i18n("Word Completion Plugin");
}

TQString DocWordCompletionPlugin::configPageFullName( uint ) const
{
  return i18n("Configure the Word Completion Plugin");
}

// FIXME provide sucn a icon
       TQPixmap DocWordCompletionPlugin::configPagePixmap( uint, int size ) const
{
  return UserIcon( "kte_wordcompletion", size );
}
//END

//BEGIN DocWordCompletionPluginView
struct DocWordCompletionPluginViewPrivate
{
  uint line, col;       // start position of last match (where to search from)
  uint cline, ccol;     // cursor position
  uint lilen;           // length of last insertion
  TQString last;         // last word we were trying to match
  TQString lastIns;      // latest applied completion
  TQRegExp re;           // hrm
  KToggleAction *autopopup; // for accessing state
  uint treshold;        // the required length of a word before popping up the completion list automatically
  int directionalPos;   // be able to insert "" at the correct time
};

DocWordCompletionPluginView::DocWordCompletionPluginView( uint treshold, bool autopopup, KTextEditor::View *view, const char *name )
  : TQObject( view, name ),
    KXMLGUIClient( view ),
    m_view( view ),
    d( new DocWordCompletionPluginViewPrivate )
{
  d->treshold = treshold;
  view->insertChildClient( this );
  setInstance( KGenericFactory<DocWordCompletionPlugin>::instance() );

  (void) new KAction( i18n("Reuse Word Above"), CTRL+Key_8, this,
    TQT_SLOT(completeBackwards()), actionCollection(), "doccomplete_bw" );
  (void) new KAction( i18n("Reuse Word Below"), CTRL+Key_9, this,
    TQT_SLOT(completeForwards()), actionCollection(), "doccomplete_fw" );
  (void) new KAction( i18n("Pop Up Completion List"), 0, this,
    TQT_SLOT(popupCompletionList()), actionCollection(), "doccomplete_pu" );
  (void) new KAction( i18n("Shell Completion"), 0, this,
    TQT_SLOT(shellComplete()), actionCollection(), "doccomplete_sh" );
  d->autopopup = new KToggleAction( i18n("Automatic Completion Popup"), 0, this,
    TQT_SLOT(toggleAutoPopup()), actionCollection(), "enable_autopopup" );

  d->autopopup->setChecked( autopopup );
  toggleAutoPopup();

  setXMLFile("docwordcompletionui.rc");

  KTextEditor::VariableInterface *vi = KTextEditor::variableInterface( view->document() );
  if ( vi )
  {
    TQString e = vi->variable("wordcompletion-autopopup");
    if ( ! e.isEmpty() )
      d->autopopup->setEnabled( e == "true" );

    connect( view->document(), TQT_SIGNAL(variableChanged(const TQString &, const TQString &)),
             this, TQT_SLOT(slotVariableChanged(const TQString &, const TQString &)) );
  }
}

void DocWordCompletionPluginView::settreshold( uint t )
{
  d->treshold = t;
}

void DocWordCompletionPluginView::completeBackwards()
{
  complete( false );
}

void DocWordCompletionPluginView::completeForwards()
{
  complete();
}

// Pop up the editors completion list if applicable
void DocWordCompletionPluginView::popupCompletionList( TQString w )
{
  if ( w.isEmpty() )
    w = word();
  if ( w.isEmpty() )
    return;

  KTextEditor::CodeCompletionInterface *cci = codeCompletionInterface( m_view );
  cci->showCompletionBox( allMatches( w ), w.length() );
}

void DocWordCompletionPluginView::toggleAutoPopup()
{
  if ( d->autopopup->isChecked() ) {
    if ( ! connect( m_view->document(), TQT_SIGNAL(charactersInteractivelyInserted(int ,int ,const TQString&)),
         this, TQT_SLOT(autoPopupCompletionList()) ))
    {
      connect( m_view->document(), TQT_SIGNAL(textChanged()), this, TQT_SLOT(autoPopupCompletionList()) );
    }
  } else {
    disconnect( m_view->document(), TQT_SIGNAL(textChanged()), this, TQT_SLOT(autoPopupCompletionList()) );
    disconnect( m_view->document(), TQT_SIGNAL(charactersInteractivelyInserted(int ,int ,const TQString&)),
                this, TQT_SLOT(autoPopupCompletionList()) );

  }
}

// for autopopup FIXME - don't pop up if reuse word is inserting
void DocWordCompletionPluginView::autoPopupCompletionList()
{
  if ( ! m_view->hasFocus() ) return;
  TQString w = word();
  if ( w.length() >= d->treshold )
  {
      popupCompletionList( w );
  }
}

// Contributed by <brain@hdsnet.hu>
void DocWordCompletionPluginView::shellComplete()
{
    // setup
  KTextEditor::EditInterface * ei = KTextEditor::editInterface(m_view->document());
    // find the word we are typing
  uint cline, ccol;
  viewCursorInterface(m_view)->cursorPositionReal(&cline, &ccol);
  TQString wrd = word();
  if (wrd.isEmpty())
    return;

  TQValueList < KTextEditor::CompletionEntry > matches = allMatches(wrd);
  if (matches.size() == 0)
    return;
  TQString partial = findLongestUnique(matches);
  if (partial.length() == wrd.length())
  {
    KTextEditor::CodeCompletionInterface * cci = codeCompletionInterface(m_view);
    cci->showCompletionBox(matches, wrd.length());
  }
  else
  {
    partial.remove(0, wrd.length());
    ei->insertText(cline, ccol, partial);
  }
}

// Do one completion, searching in the desired direction,
// if possible
void DocWordCompletionPluginView::complete( bool fw )
{
  // setup
  KTextEditor::EditInterface *ei = KTextEditor::editInterface( m_view->document() );
  // find the word we are typing
  uint cline, ccol;
  viewCursorInterface( m_view )->cursorPositionReal( &cline, &ccol );
  TQString wrd = word();
  if ( wrd.isEmpty() )
    return;

  int inc = fw ? 1 : -1;

  /* IF the current line is equal to the previous line
     AND the position - the length of the last inserted string
          is equal to the old position
     AND the lastinsertedlength last characters of the word is
          equal to the last inserted string
          */
  if ( cline == d-> cline &&
          ccol - d->lilen == d->ccol &&
          wrd.endsWith( d->lastIns ) )
  {
    // this is a repeted activation

    // if we are back to where we started, reset.
    if ( ( fw && d->directionalPos == -1 ) ||
         ( !fw && d->directionalPos == 1 ) )
    {
      if ( d->lilen )
        ei->removeText( d->cline, d->ccol, d->cline, d->ccol + d->lilen );

      d->lastIns = "";
      d->lilen = 0;
      d->line = d->cline;
      d->col = d->ccol;
      d->directionalPos = 0;

      return;
    }

    if ( fw )
      d->col += d->lilen;

    ccol = d->ccol;
    wrd = d->last;

    d->directionalPos += inc;
  }
  else
  {
    d->cline = cline;
    d->ccol = ccol;
    d->last = wrd;
    d->lastIns = "";
    d->line = cline;
    d->col = ccol - wrd.length();
    d->lilen = 0;
    d->directionalPos = inc;
  }

  d->re.setPattern( "\\b" + wrd + "(\\w+)" );
  int pos ( 0 );
  TQString ln = ei->textLine( d->line );

  while ( true )
  {
    pos = fw ?
      d->re.search( ln, d->col ) :
      d->re.searchRev( ln, d->col );

    if ( pos > -1 ) // we matched a word
    {
      TQString m = d->re.cap( 1 );
      if ( m != d->lastIns )
      {
        // we got good a match! replace text and return.
        if ( d->lilen )
          ei->removeText( d->cline, d->ccol, d->cline, d->ccol + d->lilen );
        ei->insertText( d->cline, d->ccol, m );

        d->lastIns = m;
        d->lilen = m.length();
        d->col = pos; // for next try

        return;
      }

      // equal to last one, continue
      else
      {
        d->col = pos; // for next try

        if ( fw )
          d->col += d->re.matchedLength();

        else
        {
          if ( pos == 0 )
          {
            if ( d->line > 0 )
            {
              d->line += inc;
              ln = ei->textLine( d->line );
              d->col = ln.length();
            }
            else
            {
              KNotifyClient::beep();
              return;
            }
          }

          else
            d->col--;
        }
      }
    }

    else  // no match
    {
      if ( (! fw && d->line == 0 ) || ( fw && d->line >= (uint)ei->numLines() ) )
      {
        KNotifyClient::beep();
        return;
      }

      d->line += inc;

      ln = ei->textLine( d->line );
      d->col = fw ? 0 : ln.length();
    }
  } // while true
}

// Contributed by <brain@hdsnet.hu>
TQString DocWordCompletionPluginView::findLongestUnique(const TQValueList < KTextEditor::CompletionEntry > &matches)
{
  TQString partial = matches.front().text;
  TQValueList < KTextEditor::CompletionEntry >::const_iterator i = matches.begin();
  for (++i; i != matches.end(); ++i)
  {
    if (!(*i).text.startsWith(partial))
    {
      while(partial.length() > 0)
      {
        partial.remove(partial.length() - 1, 1);
        if ((*i).text.startsWith(partial))
        {
          break;
        }
      }
      if (partial.length() == 0)
        return TQString();
    }
  }

  return partial;
}

// Return the string to complete (the letters behind the cursor)
TQString DocWordCompletionPluginView::word()
{
  uint cline, ccol;
  viewCursorInterface( m_view )->cursorPositionReal( &cline, &ccol );
  if ( ! ccol ) return TQString::null; // no word
  KTextEditor::EditInterface *ei = KTextEditor::editInterface( m_view->document() );
  d->re.setPattern( "\\b(\\w+)$" );
  if ( d->re.searchRev(
        ei->text( cline, 0, cline, ccol )
        ) < 0 )
    return TQString::null; // no word
  return d->re.cap( 1 );
}

// Scan throught the entire document for possible completions,
// ignoring any dublets
TQValueList<KTextEditor::CompletionEntry> DocWordCompletionPluginView::allMatches( const TQString &word )
{
  TQValueList<KTextEditor::CompletionEntry> l;
  uint i( 0 );
  int pos( 0 );
  d->re.setPattern( "\\b("+word+"\\w+)" );
  TQString s, m;
  KTextEditor::EditInterface *ei = KTextEditor::editInterface( m_view->document() );
  TQDict<int> seen; // maybe slow with > 17 matches
  int sawit(1);    // to ref for the dict
  uint cline, ccol;// needed to avoid constructing a word at cursor position
  viewCursorInterface( m_view )->cursorPositionReal( &cline, &ccol );

  while( i < ei->numLines() )
  {
    s = ei->textLine( i );
    pos = 0;
    while ( pos >= 0 )
    {
      pos = d->re.search( s, pos );
      if ( pos >= 0 )
      {
        // do not construct a new word!
        if ( i == cline && pos + word.length() == ccol )
        {
          pos += word.length();
          continue;
        }

        m = d->re.cap( 1 );
        if ( ! seen[ m ] ) {
          seen.insert( m, &sawit );
          KTextEditor::CompletionEntry e;
          e.text = m;
          l.append( e );
        }
        pos += d->re.matchedLength();
      }
    }
    i++;
  }
  return l;
}

void DocWordCompletionPluginView::slotVariableChanged( const TQString &var, const TQString &val )
{
  if ( var == "wordcompletion-autopopup" )
    d->autopopup->setEnabled( val == "true" );
  else if ( var == "wordcompletion-treshold" )
    d->treshold = val.toInt();
}
//END

//BEGIN DocWordCompletionConfigPage
DocWordCompletionConfigPage::DocWordCompletionConfigPage( DocWordCompletionPlugin *completion, TQWidget *parent, const char *name )
  : KTextEditor::ConfigPage( parent, name )
  , m_completion( completion )
{
  TQVBoxLayout *lo = new TQVBoxLayout( this );
  lo->setSpacing( KDialog::spacingHint() );

  cbAutoPopup = new TQCheckBox( i18n("Automatically &show completion list"), this );
  lo->addWidget( cbAutoPopup );

  TQHBox *hb = new TQHBox( this );
  hb->setSpacing( KDialog::spacingHint() );
  lo->addWidget( hb );
  TQLabel *l = new TQLabel( i18n(
      "Translators: This is the first part of two strings wich will comprise the "
      "sentence 'Show completions when a word is at least N characters'. The first "
      "part is on the right side of the N, which is represented by a spinbox "
      "widget, followed by the second part: 'characters long'. Characters is a "
      "ingeger number between and including 1 and 30. Feel free to leave the "
      "second part of the sentence blank if it suits your language better. ",
      "Show completions &when a word is at least"), hb );
  sbAutoPopup = new TQSpinBox( 1, 30, 1, hb );
  l->setBuddy( sbAutoPopup );
  lSbRight = new TQLabel( i18n(
      "This is the second part of two strings that will comprise teh sentence "
      "'Show completions when a word is at least N characters'",
      "characters long."), hb );

  TQWhatsThis::add( cbAutoPopup, i18n(
      "Enable the automatic completion list popup as default. The popup can "
      "be disabled on a view basis from the 'Tools' menu.") );
  TQWhatsThis::add( sbAutoPopup, i18n(
      "Define the length a word should have before the completion list "
      "is displayed.") );

  cbAutoPopup->setChecked( m_completion->autoPopupEnabled() );
  sbAutoPopup->setValue( m_completion->treshold() );

  lo->addStretch();
}

void DocWordCompletionConfigPage::apply()
{
  m_completion->setAutoPopupEnabled( cbAutoPopup->isChecked() );
  m_completion->setTreshold( sbAutoPopup->value() );
  m_completion->writeConfig();
}

void DocWordCompletionConfigPage::reset()
{
  cbAutoPopup->setChecked( m_completion->autoPopupEnabled() );
  sbAutoPopup->setValue( m_completion->treshold() );
}

void DocWordCompletionConfigPage::defaults()
{
  cbAutoPopup->setChecked( true );
  sbAutoPopup->setValue( 3 );
}

//END DocWordCompletionConfigPage

#include "docwordcompletion.moc"
// kate: space-indent on; indent-width 2; replace-tabs on; mixed-indent off;