]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCompleter.cpp
4b592dcad72961e8f3ed0c4de1aa19f45298442b
[lyx.git] / src / frontends / qt4 / GuiCompleter.cpp
1 /**
2  * \file GuiCompleter.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Stefan Schimanski
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "GuiCompleter.h"
14
15 #include "Buffer.h"
16 #include "BufferView.h"
17 #include "CompletionList.h"
18 #include "Cursor.h"
19 #include "Dimension.h"
20 #include "FuncRequest.h"
21 #include "GuiWorkArea.h"
22 #include "GuiView.h"
23 #include "LyXFunc.h"
24 #include "LyXRC.h"
25 #include "Paragraph.h"
26 #include "version.h"
27
28 #include "support/lassert.h"
29 #include "support/debug.h"
30
31 #include <QApplication>
32 #include <QHeaderView>
33 #include <QPainter>
34 #include <QPixmapCache>
35 #include <QScrollBar>
36 #include <QItemDelegate>
37 #include <QTreeView>
38 #include <QTimer>
39
40 using namespace std;
41 using namespace lyx::support;
42
43 namespace lyx {
44 namespace frontend {
45
46 class CompleterItemDelegate : public QItemDelegate
47 {
48 public:
49         explicit CompleterItemDelegate(QObject * parent)
50                 : QItemDelegate(parent)
51         {}
52
53         ~CompleterItemDelegate()
54         {}
55
56 protected:
57         void drawDisplay(QPainter * painter,
58                 QStyleOptionViewItem const & option,
59                 QRect const & rect, QString const & text) const
60         {
61                 QItemDelegate::drawDisplay(painter, option, rect, text);
62         }
63
64         void paint(QPainter *painter, const QStyleOptionViewItem &option,
65                    const QModelIndex &index) const
66         {
67                 if (index.column() == 0) {
68                         QItemDelegate::paint(painter, option, index);
69                         return;
70                 }
71                 QStyleOptionViewItem opt = setOptions(index, option);
72                 QVariant value = index.data(Qt::DisplayRole);
73                 QPixmap pixmap = qvariant_cast<QPixmap>(value);
74                 
75                 // draw
76                 painter->save();
77                 drawBackground(painter, opt, index);
78                 if (!pixmap.isNull()) {
79                         const QSize size = pixmap.size();
80                         painter->drawPixmap(option.rect.left() + (16 - size.width()) / 2,
81                                 option.rect.top() + (option.rect.height() - size.height()) / 2,
82                                 pixmap);
83                 }
84                 drawFocus(painter, opt, option.rect);
85                 painter->restore();
86         }
87 };
88
89 class GuiCompletionModel : public QAbstractListModel
90 {
91 public:
92         ///
93         GuiCompletionModel(QObject * parent, CompletionList const * l)
94                 : QAbstractListModel(parent), list_(l)
95         {}
96         ///
97         ~GuiCompletionModel() { delete list_; }
98         ///
99         void setList(CompletionList const * l) {
100                 delete list_;
101                 list_ = l;
102                 reset();
103         }
104         ///
105         bool sorted() const
106         {
107                 if (list_)
108                         return list_->sorted();
109                 return false;
110         }
111         ///
112         int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const
113         {
114                 return 2;
115         }
116         ///
117         int rowCount(const QModelIndex & /*parent*/ = QModelIndex()) const
118         {
119                 if (list_ == 0)
120                         return 0;
121                 else
122                         return list_->size();
123         }
124
125         ///
126         QVariant data(const QModelIndex & index, int role) const
127         {
128                 if (list_ == 0)
129                         return QVariant();
130
131                 if (index.row() < 0 || index.row() >= rowCount())
132                         return QVariant();
133
134                 if (role != Qt::DisplayRole && role != Qt::EditRole)
135                     return QVariant();
136                     
137                 if (index.column() == 0)
138                         return toqstr(list_->data(index.row()));
139
140                 if (index.column() == 1) {
141                         // get icon from cache
142                         QPixmap scaled;
143                         QString const name = ":" + toqstr(list_->icon(index.row()));
144                         if (!QPixmapCache::find("completion" + name, scaled)) {
145                                 // load icon from disk
146                                 QPixmap p = QPixmap(name);
147                                 if (!p.isNull()) {
148                                         // scale it to 16x16 or smaller
149                                         scaled = p.scaled(min(16, p.width()), min(16, p.height()), 
150                                                 Qt::KeepAspectRatio, Qt::SmoothTransformation);
151                                 }
152
153                                 QPixmapCache::insert("completion" + name, scaled);
154                         }
155                         return scaled;
156                 }
157                 return QVariant();
158         }
159
160 private:
161         /// owned by us
162         CompletionList const * list_;
163 };
164
165
166 GuiCompleter::GuiCompleter(GuiWorkArea * gui, QObject * parent)
167         : QCompleter(parent), gui_(gui), updateLock_(0),
168           inlineVisible_(false), popupVisible_(false),
169           modelActive_(false)
170 {
171         // Setup the completion popup
172         model_ = new GuiCompletionModel(this, 0);
173         setModel(model_);
174         setCompletionMode(QCompleter::PopupCompletion);
175         setWidget(gui_);
176         
177         // create the popup
178         QTreeView *listView = new QTreeView;
179         listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
180         listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
181         listView->setSelectionBehavior(QAbstractItemView::SelectRows);
182         listView->setSelectionMode(QAbstractItemView::SingleSelection);
183         listView->header()->hide();
184         listView->setIndentation(0);
185         listView->setUniformRowHeights(true);
186         setPopup(listView);
187         
188         itemDelegate_ = new CompleterItemDelegate(this);
189         popup()->setItemDelegate(itemDelegate_);
190         
191         // create timeout timers
192         popup_timer_.setSingleShot(true);
193         inline_timer_.setSingleShot(true);
194         connect(this, SIGNAL(highlighted(const QString &)),
195                 this, SLOT(popupHighlighted(const QString &)));
196         connect(this, SIGNAL(activated(const QString &)),
197                 this, SLOT(popupActivated(const QString &)));
198         connect(&popup_timer_, SIGNAL(timeout()),
199                 this, SLOT(showPopup()));
200         connect(&inline_timer_, SIGNAL(timeout()),
201                 this, SLOT(showInline()));
202 }
203
204
205 GuiCompleter::~GuiCompleter()
206 {
207         popup()->hide();
208 }
209
210
211 bool GuiCompleter::eventFilter(QObject * watched, QEvent * e)
212 {
213         // hijack back the tab key from the popup
214         // (which stole it from the workspace before)
215         if (e->type() == QEvent::KeyPress && popupVisible()) {
216                 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
217                 switch (ke->key()) {
218                 case Qt::Key_Tab:
219                         tab();
220                         ke->accept();
221                         return true;
222                 default: break;
223                 }
224         }
225         
226         return QCompleter::eventFilter(watched, e);
227 }
228
229
230 bool GuiCompleter::popupPossible(Cursor const & cur) const
231 {
232         return QApplication::activeWindow()
233                 && gui_->hasFocus()
234                 && cur.inset().completionSupported(cur);
235 }
236
237
238 bool GuiCompleter::inlinePossible(Cursor const & cur) const
239 {
240         return cur.inset().inlineCompletionSupported(cur);
241 }
242
243
244 bool GuiCompleter::completionAvailable() const
245 {
246         if (!modelActive_)
247                 return false;
248
249         size_t n = popup()->model()->rowCount();
250
251         // if there is exactly one, we have to check whether it is a 
252         // real completion, i.e. longer than the current prefix.
253         if (n == 1 && completionPrefix() == currentCompletion())
254             return false;
255
256         return n > 0;
257 }
258
259
260 bool GuiCompleter::popupVisible() const
261 {
262         return popupVisible_;
263 }
264
265
266 bool GuiCompleter::inlineVisible() const
267 {
268         // In fact using BufferView::inlineCompletionPos.empty() should be
269         // here. But unfortunately this information is not good enough
270         // because destructive operations like backspace might invalidate
271         // inlineCompletionPos. But then the completion should stay visible
272         // (i.e. reshown on the next update). Hence be keep this information
273         // in the inlineVisible_ variable.
274         return inlineVisible_;
275 }
276
277
278 void GuiCompleter::updateVisibility(Cursor & cur, bool start, bool keep, bool cursorInView)
279 {
280         // parameters which affect the completion
281         bool moved = cur != old_cursor_;
282         if (moved)
283                 old_cursor_ = cur;
284
285         bool possiblePopupState = popupPossible(cur) && cursorInView;
286         bool possibleInlineState = inlinePossible(cur) && cursorInView;
287
288         // we moved or popup state is not ok for popup?
289         if ((moved && !keep) || !possiblePopupState)
290                 hidePopup(cur);
291
292         // we moved or inline state is not ok for inline completion?
293         if ((moved && !keep) || !possibleInlineState)
294                 hideInline(cur);
295
296         // we inserted something and are in a possible popup state?
297         if (!popupVisible() && possiblePopupState && start
298                 && cur.inset().automaticPopupCompletion())
299                 popup_timer_.start(int(lyxrc.completion_popup_delay * 1000));
300
301         // we inserted something and are in a possible inline completion state?
302         if (!inlineVisible() && possibleInlineState && start
303                 && cur.inset().automaticInlineCompletion())
304                 inline_timer_.start(int(lyxrc.completion_inline_delay * 1000));
305
306         // update prefix if any completion is possible
307         bool modelActive = modelActive_ && model()->rowCount() > 0;
308         if (possiblePopupState || possibleInlineState) {
309                 if (modelActive)
310                         updatePrefix(cur);
311                 else
312                         updateAvailability();
313         }
314 }
315
316
317 void GuiCompleter::updateVisibility(bool start, bool keep)
318 {
319         Cursor cur = gui_->bufferView().cursor();
320         cur.updateFlags(Update::None);
321         
322         updateVisibility(cur, start, keep);
323         
324         if (cur.disp_.update())
325                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
326 }
327
328
329 void GuiCompleter::updatePrefix(Cursor & cur)
330 {
331         // get new prefix. Do nothing if unchanged
332         QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
333         if (newPrefix == completionPrefix())
334                 return;
335         
336         // value which should be kept selected
337         QString old = currentCompletion();
338         if (old.length() == 0)
339                 old = last_selection_;
340         
341         // update completer to new prefix
342         setCompletionPrefix(newPrefix);
343
344         // update popup because its size might have changed
345         if (popupVisible())
346                 updatePopup(cur);
347
348         // restore old selection
349         setCurrentCompletion(old);
350         
351         // if popup is not empty, the new selection will
352         // be our last valid one
353         QString const & s = currentCompletion();
354         if (popupVisible() || inlineVisible()) {
355                 if (s.length() > 0)
356                         last_selection_ = s;
357                 else
358                         last_selection_ = old;
359         }
360
361         // update inline completion because the default
362         // completion string might have changed
363         if (inlineVisible())
364                 updateInline(cur, s);
365 }
366
367
368 void GuiCompleter::updateInline(Cursor & cur, QString const & completion)
369 {
370         if (!cur.inset().inlineCompletionSupported(cur))
371                 return;
372         
373         // compute postfix
374         docstring prefix = cur.inset().completionPrefix(cur);
375         docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
376         
377         // shorten it if necessary
378         if (lyxrc.completion_inline_dots != -1
379             && postfix.size() > unsigned(lyxrc.completion_inline_dots))
380                 postfix = postfix.substr(0, lyxrc.completion_inline_dots - 1) + "...";
381
382         // set inline completion at cursor position
383         size_t uniqueTo = max(longestUniqueCompletion().size(), prefix.size());
384         gui_->bufferView().setInlineCompletion(cur, cur, postfix, uniqueTo - prefix.size());
385         inlineVisible_ = true;
386 }
387
388
389 void GuiCompleter::updatePopup(Cursor & cur)
390 {
391         if (!cur.inset().completionSupported(cur))
392                 return;
393         
394         popupVisible_ = true;
395
396         if (completionCount() == 0) {
397                 QTimer::singleShot(0, popup(), SLOT(hide()));
398                 return;
399         }
400
401         QTimer::singleShot(0, this, SLOT(asyncUpdatePopup()));
402 }
403
404
405 void GuiCompleter::asyncUpdatePopup()
406 {
407         Cursor cur = gui_->bufferView().cursor();
408         if (!cur.inset().completionSupported(cur)) {
409                 popupVisible_ = false;
410                 return;
411         }
412
413         // get dimensions of completion prefix
414         Dimension dim;
415         int x;
416         int y;
417         cur.inset().completionPosAndDim(cur, x, y, dim);
418         
419         // and calculate the rect of the popup
420         QRect rect;
421         if (popup()->layoutDirection() == Qt::RightToLeft)
422                 rect = QRect(x + dim.width() - 200, y - dim.ascent() - 3, 200, dim.height() + 6);
423         else
424                 rect = QRect(x, y - dim.ascent() - 3, 200, dim.height() + 6);
425         
426         // Resize the columns in the popup.
427         // This should really be in the constructor. But somehow the treeview
428         // has a bad memory about it and we have to tell him again and again.
429         QTreeView * listView = static_cast<QTreeView *>(popup());
430         listView->header()->setStretchLastSection(false);
431         listView->header()->setResizeMode(0, QHeaderView::Stretch);
432         listView->header()->setResizeMode(1, QHeaderView::Fixed);
433         listView->header()->resizeSection(1, 22);
434         
435         // show/update popup
436         complete(rect);
437 }
438
439
440 void GuiCompleter::updateAvailability()
441 {
442         // this should really only be of interest if no completion is
443         // visible yet, i.e. especially if automatic completion is disabled.
444         if (inlineVisible() || popupVisible())
445                 return;
446         Cursor & cur = gui_->bufferView().cursor();
447         if (!popupPossible(cur) && !inlinePossible(cur))
448                 return;
449         
450         updateModel(cur, false, false);
451 }
452         
453
454 void GuiCompleter::updateModel(Cursor & cur, bool popupUpdate, bool inlineUpdate)
455 {
456         // value which should be kept selected
457         QString old = currentCompletion();
458         if (old.length() == 0)
459                 old = last_selection_;
460
461
462         // set whether rtl
463         bool rtl = false;
464         if (cur.inTexted()) {
465                 Paragraph const & par = cur.paragraph();
466                 Font const font =
467                         par.getFontSettings(cur.bv().buffer().params(), cur.pos());
468                 rtl = font.isVisibleRightToLeft();
469         }
470         popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
471
472         // set new model
473         CompletionList const * list = cur.inset().createCompletionList(cur);
474         model_->setList(list);
475         modelActive_ = true;
476         if (list->sorted())
477                 setModelSorting(QCompleter::CaseSensitivelySortedModel);
478         else
479                 setModelSorting(QCompleter::UnsortedModel);
480
481         // set prefix
482         QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
483         if (newPrefix != completionPrefix())
484                 setCompletionPrefix(newPrefix);
485
486         // show popup
487         if (popupUpdate)
488                 updatePopup(cur);
489
490         // restore old selection
491         setCurrentCompletion(old);
492         
493         // if popup is not empty, the new selection will
494         // be our last valid one
495         if (popupVisible() || inlineVisible()) {
496                 QString const & s = currentCompletion();
497                 if (s.length() > 0)
498                         last_selection_ = s;
499                 else
500                         last_selection_ = old;
501         }
502
503         // show inline completion
504         if (inlineUpdate)
505                 updateInline(cur, currentCompletion());
506 }
507
508
509 void GuiCompleter::showPopup(Cursor & cur)
510 {
511         if (!popupPossible(cur))
512                 return;
513         
514         updateModel(cur, true, inlineVisible());
515 }
516
517
518 void GuiCompleter::hidePopup(Cursor &)
519 {
520         popupVisible_ = false;
521
522         if (popup_timer_.isActive())
523                 popup_timer_.stop();
524
525         // hide popup asynchronously because we might be here inside of
526         // LFUN dispatchers. Hiding a popup can trigger a focus event on the 
527         // workarea which then redisplays the cursor. But the metrics are not
528         // yet up to date such that the coord cache has not all insets yet. The
529         // cursorPos methods would triggers asserts in the coord cache then.
530         QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
531         
532         // mark that the asynchronous part will reset the model
533         if (!inlineVisible())
534                 modelActive_ = false;
535 }
536
537
538 void GuiCompleter::asyncHidePopup()
539 {
540         popup()->hide();
541         if (!inlineVisible())
542                 model_->setList(0);
543 }
544
545
546 void GuiCompleter::showInline(Cursor & cur)
547 {
548         if (!inlinePossible(cur))
549                 return;
550         
551         updateModel(cur, popupVisible(), true);
552 }
553
554
555 void GuiCompleter::hideInline(Cursor & cur)
556 {
557         gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
558         inlineVisible_ = false;
559         
560         if (inline_timer_.isActive())
561                 inline_timer_.stop();
562         
563         // Trigger asynchronous part of hideInline. We might be
564         // in a dispatcher here and the setModel call might
565         // trigger focus events which is are not healthy here.
566         QTimer::singleShot(0, this, SLOT(asyncHideInline()));
567
568         // mark that the asynchronous part will reset the model
569         if (!popupVisible())
570                 modelActive_ = false;
571 }
572
573
574 void GuiCompleter::asyncHideInline()
575 {
576         if (!popupVisible())
577                 model_->setList(0);
578 }
579
580
581 void GuiCompleter::showPopup()
582 {
583         Cursor cur = gui_->bufferView().cursor();
584         cur.updateFlags(Update::None);
585         
586         showPopup(cur);
587
588         // redraw if needed
589         if (cur.disp_.update())
590                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
591 }
592
593
594 void GuiCompleter::showInline()
595 {
596         Cursor cur = gui_->bufferView().cursor();
597         cur.updateFlags(Update::None);
598         
599         showInline(cur);
600
601         // redraw if needed
602         if (cur.disp_.update())
603                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
604 }
605
606
607 void GuiCompleter::hidePopup()
608 {
609         Cursor cur = gui_->bufferView().cursor();
610         cur.updateFlags(Update::None);
611         
612         hidePopup(cur);
613         
614         // redraw if needed
615         if (cur.disp_.update())
616                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
617 }
618
619
620 void GuiCompleter::hideInline()
621 {
622         Cursor cur = gui_->bufferView().cursor();
623         cur.updateFlags(Update::None);
624         
625         hideInline(cur);
626         
627         // redraw if needed
628         if (cur.disp_.update())
629                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
630 }
631
632
633 void GuiCompleter::activate()
634 {
635         if (!popupVisible() && !inlineVisible())
636                 return;
637
638         popupActivated(currentCompletion());
639 }
640
641
642 void GuiCompleter::tab()
643 {
644         BufferView * bv = &gui_->bufferView();
645         Cursor cur = bv->cursor();
646         cur.updateFlags(Update::None);
647         
648         // check that inline completion is active
649         if (!inlineVisible()) {
650                 // try to activate the inline completion
651                 if (cur.inset().inlineCompletionSupported(cur)) {
652                         showInline();
653                         
654                         // show popup without delay because the completion was not unique
655                         if (lyxrc.completion_popup_after_complete
656                             && !popupVisible()
657                             && popup()->model()->rowCount() > 1)
658                                 popup_timer_.start(0);
659
660                         return;
661                 }
662                 // or try popup
663                 if (!popupVisible() && cur.inset().completionSupported(cur)) {
664                         showPopup();
665                         return;
666                 }
667                 
668                 return;
669         }
670         
671         // If completion is active, at least complete by one character
672         docstring prefix = cur.inset().completionPrefix(cur);
673         docstring completion = qstring_to_ucs4(currentCompletion());
674         if (completion.size() <= prefix.size()) {
675                 // finalize completion
676                 cur.inset().insertCompletion(cur, docstring(), true);
677                 
678                 // hide popup and inline completion
679                 hidePopup(cur);
680                 hideInline(cur);
681                 updateVisibility(false, false);
682                 return;
683         }
684         docstring nextchar = completion.substr(prefix.size(), 1);
685         if (!cur.inset().insertCompletion(cur, nextchar, false))
686                 return;
687         updatePrefix(cur);
688
689         // try to complete as far as it is unique
690         docstring longestCompletion = longestUniqueCompletion();
691         prefix = cur.inset().completionPrefix(cur);
692         docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
693         cur.inset().insertCompletion(cur, postfix, false);
694         old_cursor_ = bv->cursor();
695         updatePrefix(cur);
696
697         // show popup without delay because the completion was not unique
698         if (lyxrc.completion_popup_after_complete
699             && !popupVisible()
700             && popup()->model()->rowCount() > 1)
701                 popup_timer_.start(0);
702
703         // redraw if needed
704         if (cur.disp_.update())
705                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
706 }
707
708
709 QString GuiCompleter::currentCompletion() const
710 {
711         if (!popup()->selectionModel()->hasSelection())
712                 return QString();
713
714         // Not sure if this is bug in Qt: currentIndex() always 
715         // return the first element in the list.
716         QModelIndex idx = popup()->currentIndex();
717         return popup()->model()->data(idx, Qt::EditRole).toString();
718 }
719
720
721 void GuiCompleter::setCurrentCompletion(QString const & s)
722 {       
723         QAbstractItemModel const & model = *popup()->model();
724         size_t n = model.rowCount();
725         if (n == 0)
726                 return;
727
728         // select the first if s is empty
729         if (s.length() == 0) {
730                 updateLock_++;
731                 popup()->setCurrentIndex(model.index(0, 0));
732                 updateLock_--;
733                 return;
734         }
735
736         // find old selection in model
737         size_t i;
738         if (modelSorting() == QCompleter::UnsortedModel) {
739                 // In unsorted models, iterate through list until the s is found
740                 for (i = 0; i < n; ++i) {
741                         QString const & is
742                         = model.data(model.index(i, 0), Qt::EditRole).toString();
743                         if (is == s)
744                                 break;
745                 }
746         } else {
747                 // In sorted models, do binary search for s.
748                 int l = 0;
749                 int r = n - 1;
750                 while (r >= l && l < int(n)) {
751                         size_t mid = (r + l) / 2;
752                         QString const & mids
753                         = model.data(model.index(mid, 0),
754                                      Qt::EditRole).toString();
755
756                         // left or right?
757                         // FIXME: is this really the same order that the docstring
758                         // from the CompletionList has?
759                         int c = s.compare(mids, Qt::CaseSensitive);
760                         if (c == 0) {
761                                 l = mid;
762                                 break;
763                         } else if (l == r) {
764                                 l = n;
765                                 break;
766                         } else if (c > 0)
767                                 // middle is not far enough
768                                 l = mid + 1;
769                         else
770                                 // middle is too far
771                                 r = mid - 1;
772                 }
773
774                 // loop was left without finding anything
775                 if (r < l)
776                         i = n;
777                 else
778                         i = l;
779                 LASSERT(i <= n, /**/);
780         }
781
782         // select the first if none was found
783         if (i == n)
784                 i = 0;
785
786         updateLock_++;
787         popup()->setCurrentIndex(model.index(i, 0));
788         updateLock_--;
789 }
790
791
792 size_t commonPrefix(QString const & s1, QString const & s2)
793 {
794         // find common prefix
795         size_t j;
796         size_t n1 = s1.length();
797         size_t n2 = s2.length();
798         for (j = 0; j < n1 && j < n2; ++j) {
799                 if (s1.at(j) != s2.at(j))
800                         break;
801         }
802         return j;
803 }
804
805
806 docstring GuiCompleter::longestUniqueCompletion() const
807 {
808         QAbstractItemModel const & model = *popup()->model();
809         size_t n = model.rowCount();
810         if (n == 0)
811                 return docstring();
812         QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
813         
814         if (modelSorting() == QCompleter::UnsortedModel) {
815                 // For unsorted model we cannot do more than iteration.
816                 // Iterate through the completions and cut off where s differs
817                 for (size_t i = 0; i < n && s.length() > 0; ++i) {
818                         QString const & is
819                         = model.data(model.index(i, 0), Qt::EditRole).toString();
820
821                         s = s.left(commonPrefix(is, s));
822                 }
823         } else {
824                 // For sorted models we can do binary search multiple times,
825                 // each time to find the first string which has s not as prefix.
826                 size_t i = 0;
827                 while (i < n && s.length() > 0) {
828                         // find first string that does not have s as prefix
829                         // via binary search in [i,n-1]
830                         size_t r = n - 1;
831                         do {
832                                 // get common prefix with the middle string
833                                 size_t mid = (r + i) / 2;
834                                 QString const & mids
835                                 = model.data(model.index(mid, 0), 
836                                         Qt::EditRole).toString();
837                                 size_t oldLen = s.length();
838                                 size_t len = commonPrefix(mids, s);
839                                 s = s.left(len);
840
841                                 // left or right?
842                                 if (oldLen == len) {
843                                         // middle is not far enough
844                                         i = mid + 1;
845                                 } else {
846                                         // middle is maybe too far
847                                         r = mid;
848                                 }
849                         } while (r - i > 0 && i < n);
850                 }
851         }
852
853         return qstring_to_ucs4(s);
854 }
855
856
857 void GuiCompleter::popupActivated(const QString & completion)
858 {
859         Cursor cur = gui_->bufferView().cursor();
860         cur.updateFlags(Update::None);
861         
862         docstring prefix = cur.inset().completionPrefix(cur);
863         docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
864         cur.inset().insertCompletion(cur, postfix, true);
865         hidePopup(cur);
866         hideInline(cur);
867         
868         if (cur.disp_.update())
869                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
870 }
871
872
873 void GuiCompleter::popupHighlighted(const QString & completion)
874 {
875         if (updateLock_ > 0)
876                 return;
877
878         Cursor cur = gui_->bufferView().cursor();
879         cur.updateFlags(Update::None);
880         
881         if (inlineVisible())
882                 updateInline(cur, completion);
883         
884         if (cur.disp_.update())
885                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
886 }
887
888 } // namespace frontend
889 } // namespace lyx
890
891 #include "GuiCompleter_moc.cpp"