]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCompleter.cpp
whitespace
[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         // set whether rtl
462         bool rtl = false;
463         if (cur.inTexted()) {
464                 Paragraph const & par = cur.paragraph();
465                 Font const font =
466                         par.getFontSettings(cur.bv().buffer().params(), cur.pos());
467                 rtl = font.isVisibleRightToLeft();
468         }
469         popup()->setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight);
470
471         // set new model
472         CompletionList const * list = cur.inset().createCompletionList(cur);
473         model_->setList(list);
474         modelActive_ = true;
475         if (list->sorted())
476                 setModelSorting(QCompleter::CaseSensitivelySortedModel);
477         else
478                 setModelSorting(QCompleter::UnsortedModel);
479
480         // set prefix
481         QString newPrefix = toqstr(cur.inset().completionPrefix(cur));
482         if (newPrefix != completionPrefix())
483                 setCompletionPrefix(newPrefix);
484
485         // show popup
486         if (popupUpdate)
487                 updatePopup(cur);
488
489         // restore old selection
490         setCurrentCompletion(old);
491         
492         // if popup is not empty, the new selection will
493         // be our last valid one
494         if (popupVisible() || inlineVisible()) {
495                 QString const & s = currentCompletion();
496                 if (s.length() > 0)
497                         last_selection_ = s;
498                 else
499                         last_selection_ = old;
500         }
501
502         // show inline completion
503         if (inlineUpdate)
504                 updateInline(cur, currentCompletion());
505 }
506
507
508 void GuiCompleter::showPopup(Cursor & cur)
509 {
510         if (!popupPossible(cur))
511                 return;
512         
513         updateModel(cur, true, inlineVisible());
514 }
515
516
517 void GuiCompleter::hidePopup(Cursor &)
518 {
519         popupVisible_ = false;
520
521         if (popup_timer_.isActive())
522                 popup_timer_.stop();
523
524         // hide popup asynchronously because we might be here inside of
525         // LFUN dispatchers. Hiding a popup can trigger a focus event on the 
526         // workarea which then redisplays the cursor. But the metrics are not
527         // yet up to date such that the coord cache has not all insets yet. The
528         // cursorPos methods would triggers asserts in the coord cache then.
529         QTimer::singleShot(0, this, SLOT(asyncHidePopup()));
530         
531         // mark that the asynchronous part will reset the model
532         if (!inlineVisible())
533                 modelActive_ = false;
534 }
535
536
537 void GuiCompleter::asyncHidePopup()
538 {
539         popup()->hide();
540         if (!inlineVisible())
541                 model_->setList(0);
542 }
543
544
545 void GuiCompleter::showInline(Cursor & cur)
546 {
547         if (!inlinePossible(cur))
548                 return;
549         
550         updateModel(cur, popupVisible(), true);
551 }
552
553
554 void GuiCompleter::hideInline(Cursor & cur)
555 {
556         gui_->bufferView().setInlineCompletion(cur, DocIterator(), docstring());
557         inlineVisible_ = false;
558         
559         if (inline_timer_.isActive())
560                 inline_timer_.stop();
561         
562         // Trigger asynchronous part of hideInline. We might be
563         // in a dispatcher here and the setModel call might
564         // trigger focus events which is are not healthy here.
565         QTimer::singleShot(0, this, SLOT(asyncHideInline()));
566
567         // mark that the asynchronous part will reset the model
568         if (!popupVisible())
569                 modelActive_ = false;
570 }
571
572
573 void GuiCompleter::asyncHideInline()
574 {
575         if (!popupVisible())
576                 model_->setList(0);
577 }
578
579
580 void GuiCompleter::showPopup()
581 {
582         Cursor cur = gui_->bufferView().cursor();
583         cur.updateFlags(Update::None);
584         
585         showPopup(cur);
586
587         // redraw if needed
588         if (cur.disp_.update())
589                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
590 }
591
592
593 void GuiCompleter::showInline()
594 {
595         Cursor cur = gui_->bufferView().cursor();
596         cur.updateFlags(Update::None);
597         
598         showInline(cur);
599
600         // redraw if needed
601         if (cur.disp_.update())
602                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
603 }
604
605
606 void GuiCompleter::hidePopup()
607 {
608         Cursor cur = gui_->bufferView().cursor();
609         cur.updateFlags(Update::None);
610         
611         hidePopup(cur);
612         
613         // redraw if needed
614         if (cur.disp_.update())
615                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
616 }
617
618
619 void GuiCompleter::hideInline()
620 {
621         Cursor cur = gui_->bufferView().cursor();
622         cur.updateFlags(Update::None);
623         
624         hideInline(cur);
625         
626         // redraw if needed
627         if (cur.disp_.update())
628                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
629 }
630
631
632 void GuiCompleter::activate()
633 {
634         if (!popupVisible() && !inlineVisible())
635                 return;
636
637         popupActivated(currentCompletion());
638 }
639
640
641 void GuiCompleter::tab()
642 {
643         BufferView * bv = &gui_->bufferView();
644         Cursor cur = bv->cursor();
645         cur.updateFlags(Update::None);
646         
647         // check that inline completion is active
648         if (!inlineVisible()) {
649                 // try to activate the inline completion
650                 if (cur.inset().inlineCompletionSupported(cur)) {
651                         showInline();
652                         
653                         // show popup without delay because the completion was not unique
654                         if (lyxrc.completion_popup_after_complete
655                             && !popupVisible()
656                             && popup()->model()->rowCount() > 1)
657                                 popup_timer_.start(0);
658
659                         return;
660                 }
661                 // or try popup
662                 if (!popupVisible() && cur.inset().completionSupported(cur)) {
663                         showPopup();
664                         return;
665                 }
666                 
667                 return;
668         }
669         
670         // If completion is active, at least complete by one character
671         docstring prefix = cur.inset().completionPrefix(cur);
672         docstring completion = qstring_to_ucs4(currentCompletion());
673         if (completion.size() <= prefix.size()) {
674                 // finalize completion
675                 cur.inset().insertCompletion(cur, docstring(), true);
676                 
677                 // hide popup and inline completion
678                 hidePopup(cur);
679                 hideInline(cur);
680                 updateVisibility(false, false);
681                 return;
682         }
683         docstring nextchar = completion.substr(prefix.size(), 1);
684         if (!cur.inset().insertCompletion(cur, nextchar, false))
685                 return;
686         updatePrefix(cur);
687
688         // try to complete as far as it is unique
689         docstring longestCompletion = longestUniqueCompletion();
690         prefix = cur.inset().completionPrefix(cur);
691         docstring postfix = longestCompletion.substr(min(longestCompletion.size(), prefix.size()));
692         cur.inset().insertCompletion(cur, postfix, false);
693         old_cursor_ = bv->cursor();
694         updatePrefix(cur);
695
696         // show popup without delay because the completion was not unique
697         if (lyxrc.completion_popup_after_complete
698             && !popupVisible()
699             && popup()->model()->rowCount() > 1)
700                 popup_timer_.start(0);
701
702         // redraw if needed
703         if (cur.disp_.update())
704                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
705 }
706
707
708 QString GuiCompleter::currentCompletion() const
709 {
710         if (!popup()->selectionModel()->hasSelection())
711                 return QString();
712
713         // Not sure if this is bug in Qt: currentIndex() always 
714         // return the first element in the list.
715         QModelIndex idx = popup()->currentIndex();
716         return popup()->model()->data(idx, Qt::EditRole).toString();
717 }
718
719
720 void GuiCompleter::setCurrentCompletion(QString const & s)
721 {       
722         QAbstractItemModel const & model = *popup()->model();
723         size_t n = model.rowCount();
724         if (n == 0)
725                 return;
726
727         // select the first if s is empty
728         if (s.length() == 0) {
729                 updateLock_++;
730                 popup()->setCurrentIndex(model.index(0, 0));
731                 updateLock_--;
732                 return;
733         }
734
735         // find old selection in model
736         size_t i;
737         if (modelSorting() == QCompleter::UnsortedModel) {
738                 // In unsorted models, iterate through list until the s is found
739                 for (i = 0; i < n; ++i) {
740                         QString const & is
741                         = model.data(model.index(i, 0), Qt::EditRole).toString();
742                         if (is == s)
743                                 break;
744                 }
745         } else {
746                 // In sorted models, do binary search for s.
747                 int l = 0;
748                 int r = n - 1;
749                 while (r >= l && l < int(n)) {
750                         size_t mid = (r + l) / 2;
751                         QString const & mids
752                         = model.data(model.index(mid, 0),
753                                      Qt::EditRole).toString();
754
755                         // left or right?
756                         // FIXME: is this really the same order that the docstring
757                         // from the CompletionList has?
758                         int c = s.compare(mids, Qt::CaseSensitive);
759                         if (c == 0) {
760                                 l = mid;
761                                 break;
762                         } else if (l == r) {
763                                 l = n;
764                                 break;
765                         } else if (c > 0)
766                                 // middle is not far enough
767                                 l = mid + 1;
768                         else
769                                 // middle is too far
770                                 r = mid - 1;
771                 }
772
773                 // loop was left without finding anything
774                 if (r < l)
775                         i = n;
776                 else
777                         i = l;
778                 LASSERT(i <= n, /**/);
779         }
780
781         // select the first if none was found
782         if (i == n)
783                 i = 0;
784
785         updateLock_++;
786         popup()->setCurrentIndex(model.index(i, 0));
787         updateLock_--;
788 }
789
790
791 size_t commonPrefix(QString const & s1, QString const & s2)
792 {
793         // find common prefix
794         size_t j;
795         size_t n1 = s1.length();
796         size_t n2 = s2.length();
797         for (j = 0; j < n1 && j < n2; ++j) {
798                 if (s1.at(j) != s2.at(j))
799                         break;
800         }
801         return j;
802 }
803
804
805 docstring GuiCompleter::longestUniqueCompletion() const
806 {
807         QAbstractItemModel const & model = *popup()->model();
808         size_t n = model.rowCount();
809         if (n == 0)
810                 return docstring();
811         QString s = model.data(model.index(0, 0), Qt::EditRole).toString();
812         
813         if (modelSorting() == QCompleter::UnsortedModel) {
814                 // For unsorted model we cannot do more than iteration.
815                 // Iterate through the completions and cut off where s differs
816                 for (size_t i = 0; i < n && s.length() > 0; ++i) {
817                         QString const & is
818                         = model.data(model.index(i, 0), Qt::EditRole).toString();
819
820                         s = s.left(commonPrefix(is, s));
821                 }
822         } else {
823                 // For sorted models we can do binary search multiple times,
824                 // each time to find the first string which has s not as prefix.
825                 size_t i = 0;
826                 while (i < n && s.length() > 0) {
827                         // find first string that does not have s as prefix
828                         // via binary search in [i,n-1]
829                         size_t r = n - 1;
830                         do {
831                                 // get common prefix with the middle string
832                                 size_t mid = (r + i) / 2;
833                                 QString const & mids
834                                 = model.data(model.index(mid, 0), 
835                                         Qt::EditRole).toString();
836                                 size_t oldLen = s.length();
837                                 size_t len = commonPrefix(mids, s);
838                                 s = s.left(len);
839
840                                 // left or right?
841                                 if (oldLen == len) {
842                                         // middle is not far enough
843                                         i = mid + 1;
844                                 } else {
845                                         // middle is maybe too far
846                                         r = mid;
847                                 }
848                         } while (r - i > 0 && i < n);
849                 }
850         }
851
852         return qstring_to_ucs4(s);
853 }
854
855
856 void GuiCompleter::popupActivated(const QString & completion)
857 {
858         Cursor cur = gui_->bufferView().cursor();
859         cur.updateFlags(Update::None);
860         
861         docstring prefix = cur.inset().completionPrefix(cur);
862         docstring postfix = qstring_to_ucs4(completion.mid(prefix.length()));
863         cur.inset().insertCompletion(cur, postfix, true);
864         hidePopup(cur);
865         hideInline(cur);
866         
867         if (cur.disp_.update())
868                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
869 }
870
871
872 void GuiCompleter::popupHighlighted(const QString & completion)
873 {
874         if (updateLock_ > 0)
875                 return;
876
877         Cursor cur = gui_->bufferView().cursor();
878         cur.updateFlags(Update::None);
879         
880         if (inlineVisible())
881                 updateInline(cur, completion);
882         
883         if (cur.disp_.update())
884                 gui_->bufferView().processUpdateFlags(cur.disp_.update());
885 }
886
887 } // namespace frontend
888 } // namespace lyx
889
890 #include "GuiCompleter_moc.cpp"