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