]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCitation.cpp
1af187aa281a73081e02ca6a2e45f65ed9ad5627
[lyx.git] / src / frontends / qt4 / GuiCitation.cpp
1
2 /**
3  * \file GuiCitation.cpp
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Angus Leeming
8  * \author Kalle Dalheimer
9  * \author Abdelrazak Younes
10  * \author Richard Heck
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "GuiCitation.h"
18
19 #include "GuiApplication.h"
20 #include "GuiSelectionManager.h"
21 #include "qt_helpers.h"
22
23 #include "Buffer.h"
24 #include "BufferView.h"
25 #include "BiblioInfo.h"
26 #include "BufferParams.h"
27 #include "TextClass.h"
28 #include "FuncRequest.h"
29
30 #include "insets/InsetCitation.h"
31 #include "insets/InsetCommand.h"
32
33 #include "support/debug.h"
34 #include "support/docstring.h"
35 #include "support/gettext.h"
36 #include "support/lstrings.h"
37
38 #include <QCloseEvent>
39 #include <QMenu>
40 #include <QSettings>
41 #include <QShowEvent>
42 #include <QStandardItemModel>
43 #include <QVariant>
44
45 #include <vector>
46 #include <string>
47
48 #undef KeyPress
49
50 #include "support/regex.h"
51
52 #include <algorithm>
53 #include <string>
54 #include <vector>
55
56 using namespace std;
57 using namespace lyx::support;
58
59 namespace lyx {
60 namespace frontend {
61
62 // FIXME THREAD
63 // I am guessing that it would not hurt to make these private members.
64 static vector<string> citeCmds_;
65 static vector<CitationStyle> citeStyles_;
66
67
68 template<typename String>
69 static QStringList to_qstring_list(vector<String> const & v)
70 {
71         QStringList qlist;
72
73         for (size_t i = 0; i != v.size(); ++i) {
74                 if (v[i].empty())
75                         continue;
76                 qlist.append(lyx::toqstr(v[i]));
77         }
78         return qlist;
79 }
80
81
82 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
83 {
84         vector<lyx::docstring> v;
85         for (int i = 0; i != qlist.size(); ++i) {
86                 if (qlist[i].isEmpty())
87                         continue;
88                 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
89         }
90         return v;
91 }
92
93
94 GuiCitation::GuiCitation(GuiView & lv)
95         : DialogView(lv, "citation", qt_("Citation")),
96           style_(QString()), params_(insetCode("citation"))
97 {
98         setupUi(this);
99
100         // The filter bar
101         filter_ = new FancyLineEdit(this);
102         filter_->setButtonPixmap(FancyLineEdit::Right, getPixmap("images/", "editclear", "svgz,png"));
103         filter_->setButtonVisible(FancyLineEdit::Right, true);
104         filter_->setButtonToolTip(FancyLineEdit::Right, qt_("Clear text"));
105         filter_->setAutoHideButton(FancyLineEdit::Right, true);
106         filter_->setPlaceholderText(qt_("All avail. citations"));
107
108         filterBarL->addWidget(filter_, 0);
109         findKeysLA->setBuddy(filter_);
110
111         // Add search options as button menu
112         regexp_ = new QAction(qt_("Regular e&xpression"), this);
113         regexp_->setCheckable(true);
114         casesense_ = new QAction(qt_("Case se&nsitive"), this);
115         casesense_->setCheckable(true);
116         instant_ = new QAction(qt_("Search as you &type"), this);
117         instant_->setCheckable(true);
118         instant_->setChecked(true);
119
120         QMenu * searchOpts = new QMenu(this);
121         searchOpts->addAction(regexp_);
122         searchOpts->addAction(casesense_);
123         searchOpts->addAction(instant_);
124         searchOptionsPB->setMenu(searchOpts);
125
126         connect(citationStyleCO, SIGNAL(activated(int)),
127                 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
128         connect(starredCB, SIGNAL(clicked()),
129                 this, SLOT(updateStyles()));
130         connect(literalCB, SIGNAL(clicked()),
131                 this, SLOT(changed()));
132         connect(forceuppercaseCB, SIGNAL(clicked()),
133                 this, SLOT(updateStyles()));
134         connect(textBeforeED, SIGNAL(textChanged(QString)),
135                 this, SLOT(updateStyles()));
136         connect(textAfterED, SIGNAL(textChanged(QString)),
137                 this, SLOT(updateStyles()));
138         connect(textBeforeED, SIGNAL(returnPressed()),
139                 this, SLOT(on_okPB_clicked()));
140         connect(textAfterED, SIGNAL(returnPressed()),
141                 this, SLOT(on_okPB_clicked()));
142
143         selectionManager = new GuiSelectionManager(this, availableLV, selectedLV,
144                         addPB, deletePB, upPB, downPB, &available_model_, &selected_model_, 1);
145         connect(selectionManager, SIGNAL(selectionChanged()),
146                 this, SLOT(setCitedKeys()));
147         connect(selectionManager, SIGNAL(updateHook()),
148                 this, SLOT(updateControls()));
149         connect(selectionManager, SIGNAL(okHook()),
150                 this, SLOT(on_okPB_clicked()));
151
152         connect(filter_, SIGNAL(rightButtonClicked()),
153                 this, SLOT(resetFilter()));
154         connect(filter_, SIGNAL(textEdited(QString)),
155                 this, SLOT(filterChanged(QString)));
156         connect(filter_, SIGNAL(returnPressed()),
157                 this, SLOT(filterPressed()));
158 #if (QT_VERSION < 0x050000)
159         connect(filter_, SIGNAL(downPressed()),
160                 availableLV, SLOT(setFocus()));
161 #else
162         connect(filter_, &FancyLineEdit::downPressed,
163                 availableLV, [=](){ focusAndHighlight(availableLV); });
164 #endif
165         connect(regexp_, SIGNAL(triggered()),
166                 this, SLOT(regexChanged()));
167         connect(casesense_, SIGNAL(triggered()),
168                 this, SLOT(caseChanged()));
169         connect(instant_, SIGNAL(triggered(bool)),
170                 this, SLOT(instantChanged(bool)));
171
172 #if (QT_VERSION < 0x050000)
173         selectedLV->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
174 #else
175         selectedLV->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
176 #endif
177
178         setFocusProxy(filter_);
179 }
180
181
182 void GuiCitation::closeEvent(QCloseEvent * e)
183 {
184         clearSelection();
185         DialogView::closeEvent(e);
186 }
187
188
189 void GuiCitation::applyView()
190 {
191         int const choice = max(0, citationStyleCO->currentIndex());
192         style_ = citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
193         bool const full  = starredCB->isChecked();
194         bool const force = forceuppercaseCB->isChecked();
195
196         QString const before = textBeforeED->text();
197         QString const after = textAfterED->text();
198
199         applyParams(choice, full, force, before, after);
200 }
201
202
203 void GuiCitation::showEvent(QShowEvent * e)
204 {
205         filter_->clear();
206         availableLV->setFocus();
207         DialogView::showEvent(e);
208 }
209
210
211 void GuiCitation::on_okPB_clicked()
212 {
213         applyView();
214         clearSelection();
215         hide();
216 }
217
218
219 void GuiCitation::on_cancelPB_clicked()
220 {
221         clearSelection();
222         hide();
223 }
224
225
226 void GuiCitation::on_applyPB_clicked()
227 {
228         applyView();
229 }
230
231
232 void GuiCitation::on_restorePB_clicked()
233 {
234         init();
235         updateFilterHint();
236         filterPressed();
237 }
238
239
240 void GuiCitation::on_literalCB_clicked()
241 {
242         InsetCitation::last_literal = literalCB->isChecked();
243         changed();
244 }
245
246
247 void GuiCitation::updateControls()
248 {
249         BiblioInfo const & bi = bibInfo();
250         updateControls(bi);
251 }
252
253
254 // The main point of separating this out is that the fill*() methods
255 // called in update() do not need to be called for INTERNAL updates,
256 // such as when addPB is pressed, as the list of fields, entries, etc,
257 // will not have changed.
258 void GuiCitation::updateControls(BiblioInfo const & bi)
259 {
260         QModelIndex idx = selectionManager->getSelectedIndex(1);
261         updateInfo(bi, idx);
262         int i = citationStyleCO->currentIndex();
263         if (i == -1 || i > int(citeStyles_.size()))
264                 i = 0;
265         updateFormatting(citeStyles_[i]);
266         selectionManager->update();
267 }
268
269
270 void GuiCitation::updateFormatting(CitationStyle const & currentStyle)
271 {
272         BufferParams const bp = documentBuffer().params();
273         bool const force = currentStyle.forceUpperCase;
274         bool const starred = currentStyle.hasStarredVersion;
275         bool const full = starred && bp.fullAuthorList();
276         bool const textbefore = currentStyle.textBefore;
277         bool const textafter = currentStyle.textAfter;
278
279         int const rows = selectedLV->model()->rowCount();
280
281         bool const qualified = currentStyle.hasQualifiedList
282                 && (rows > 1
283                     || !params_["pretextlist"].empty()
284                     || !params_["posttextlist"].empty());
285         selectedLV->horizontalHeader()->setVisible(qualified);
286         selectedLV->setColumnHidden(0, !qualified);
287         selectedLV->setColumnHidden(2, !qualified);
288         bool const haveSelection = rows > 0;
289         if (qualified) {
290                 textBeforeLA->setText(qt_("General text befo&re:"));
291                 textAfterLA->setText(qt_("General &text after:"));
292                 textBeforeED->setToolTip(qt_("Text that precedes the whole reference list. "
293                                              "For text that precedes individual items, "
294                                              "double-click on the respective entry above."));
295                 textAfterLA->setToolTip(qt_("General &text after:"));
296                 textAfterED->setToolTip(qt_("Text that follows the whole reference list. "
297                                              "For text that follows individual items, "
298                                              "double-click on the respective entry above."));
299         } else {
300                 textBeforeLA->setText(qt_("Text befo&re:"));
301                 if (textbefore && haveSelection)
302                         textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\")"));
303                 else
304                         textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\"), "
305                                                      "if the current citation style supports this."));
306                 textAfterLA->setText(qt_("&Text after:"));
307                 if (textafter && haveSelection)
308                         textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages)"));
309                 else
310                         textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages), "
311                                                     "if the current citation style supports this."));
312         }
313
314         forceuppercaseCB->setEnabled(force && haveSelection);
315         if (force && haveSelection)
316                 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\")."));
317         else
318                 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\"), "
319                                              "if the current citation style supports this."));
320         starredCB->setEnabled(full && haveSelection);
321         textBeforeED->setEnabled(textbefore && haveSelection);
322         textBeforeLA->setEnabled(textbefore && haveSelection);
323         textAfterED->setEnabled(textafter && haveSelection);
324         textAfterLA->setEnabled(textafter && haveSelection);
325         literalCB->setEnabled(textbefore || textafter);
326         citationStyleCO->setEnabled(haveSelection);
327         citationStyleLA->setEnabled(haveSelection);
328
329         // Check if we have a custom string/tooltip for the starred version
330         if (starred && !currentStyle.stardesc.empty()) {
331                 string val =
332                         bp.documentClass().getCiteMacro(bp.citeEngineType(), currentStyle.stardesc);
333                 docstring guistring;
334                 if (!val.empty()) {
335                         guistring = translateIfPossible(from_utf8(val));
336                         starredCB->setText(toqstr(guistring));
337                         starredCB->setEnabled(haveSelection);
338                 }
339                 if (!currentStyle.startooltip.empty()) {
340                         val = bp.documentClass().getCiteMacro(bp.citeEngineType(),
341                                                               currentStyle.startooltip);
342                         if (!val.empty())
343                                 guistring = translateIfPossible(from_utf8(val));
344                 }
345                 // Tooltip might also be empty
346                 starredCB->setToolTip(toqstr(guistring));
347         } else {
348                 // This is the default meaning of the starred commands
349                 starredCB->setText(qt_("All aut&hors"));
350                 if (full && haveSelection)
351                         starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\")"));
352                 else
353                         starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\"), "
354                                                   "if the current citation style supports this."));
355         }
356 }
357
358
359 // Update the styles for the style combo, citationStyleCO, and mark the
360 // settings as changed. Called upon changing the cited keys (including
361 // merely reordering the keys) or editing the text before/after fields.
362 void GuiCitation::updateStyles()
363 {
364         BiblioInfo const & bi = bibInfo();
365         updateStyles(bi);
366         changed();
367 }
368
369
370 // Update the styles for the style combo, citationStyleCO.
371 void GuiCitation::updateStyles(BiblioInfo const & bi)
372 {
373         QStringList selected_keys = selectedKeys();
374         int curr = selectedLV->model()->rowCount() - 1;
375
376         if (curr < 0 || selected_keys.empty()) {
377                 citationStyleCO->clear();
378                 citationStyleCO->setEnabled(false);
379                 citationStyleLA->setEnabled(false);
380                 return;
381         }
382
383         static const size_t max_length = 80;
384         BiblioInfo::CiteStringMap sty = citationStyles(bi, max_length);
385
386         if (sty.empty()) {
387                 // some error
388                 citationStyleCO->setEnabled(false);
389                 citationStyleLA->setEnabled(false);
390                 citationStyleCO->clear();
391                 return;
392         }
393
394         citationStyleCO->blockSignals(true);
395
396         // save old style selection
397         QString const curdata =
398                 citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
399         QString const olddata = (curdata.isEmpty()) ? style_ : curdata;
400         citationStyleCO->clear();
401         BiblioInfo::CiteStringMap::const_iterator cit = sty.begin();
402         BiblioInfo::CiteStringMap::const_iterator end = sty.end();
403         for (int ii = 1; cit != end; ++cit, ++ii)
404                 citationStyleCO->addItem(toqstr(cit->second), toqstr(cit->first));
405         citationStyleCO->setEnabled(true);
406         citationStyleLA->setEnabled(true);
407         // restore old style selection
408         int const i = citationStyleCO->findData(olddata);
409         if (i != -1)
410                 citationStyleCO->setCurrentIndex(i);
411
412         citationStyleCO->blockSignals(false);
413 }
414
415
416 void GuiCitation::fillFields(BiblioInfo const & bi)
417 {
418         fieldsCO->blockSignals(true);
419         int const oldIndex = fieldsCO->currentIndex();
420         fieldsCO->clear();
421         QStringList const fields = to_qstring_list(bi.getFields());
422         fieldsCO->insertItem(0, qt_("All fields"));
423         fieldsCO->insertItem(1, qt_("Keys"));
424         fieldsCO->insertItems(2, fields);
425         if (oldIndex != -1 && oldIndex < fieldsCO->count())
426                 fieldsCO->setCurrentIndex(oldIndex);
427         fieldsCO->blockSignals(false);
428 }
429
430
431 void GuiCitation::fillEntries(BiblioInfo const & bi)
432 {
433         entriesCO->blockSignals(true);
434         int const oldIndex = entriesCO->currentIndex();
435         entriesCO->clear();
436         QStringList const entries = to_qstring_list(bi.getEntries());
437         entriesCO->insertItem(0, qt_("All entry types"));
438         entriesCO->insertItems(1, entries);
439         if (oldIndex != -1 && oldIndex < entriesCO->count())
440                 entriesCO->setCurrentIndex(oldIndex);
441         entriesCO->blockSignals(false);
442 }
443
444
445 bool GuiCitation::isSelected(QModelIndex const & idx)
446 {
447         QString const str = idx.data().toString();
448         return selectedKeys().contains(str);
449 }
450
451
452 void GuiCitation::setButtons()
453 {
454         int const srows = selectedLV->model()->rowCount();
455         applyPB->setEnabled(srows > 0);
456         okPB->setEnabled(srows > 0);
457 }
458
459
460 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
461 {
462         if (!idx.isValid() || bi.empty()) {
463                 infoML->document()->clear();
464                 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
465                 return;
466         }
467
468         infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
469         CiteItem ci;
470         ci.richtext = true;
471         QString const keytxt = toqstr(
472                 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), ci));
473         infoML->document()->setHtml(keytxt);
474 }
475
476
477 void GuiCitation::findText(QString const & text, bool reset)
478 {
479         //"All Fields" and "Keys" are the first two
480         int index = fieldsCO->currentIndex() - 2;
481         BiblioInfo const & bi = bibInfo();
482         vector<docstring> const & fields = bi.getFields();
483         docstring field;
484
485         if (index <= -1 || index >= int(fields.size()))
486                 //either "All Fields" or "Keys" or an invalid value
487                 field = from_ascii("");
488         else
489                 field = fields[index];
490
491         //Was it "Keys"?
492         bool const onlyKeys = index == -1;
493
494         //"All Entry Types" is first.
495         index = entriesCO->currentIndex() - 1;
496         vector<docstring> const & entries = bi.getEntries();
497         docstring entry_type;
498         if (index < 0 || index >= int(entries.size()))
499                 entry_type = from_ascii("");
500         else
501                 entry_type = entries[index];
502
503         bool const case_sentitive = casesense_->isChecked();
504         bool const reg_exp = regexp_->isChecked();
505
506         findKey(bi, text, onlyKeys, field, entry_type,
507                        case_sentitive, reg_exp, reset);
508         //FIXME
509         //It'd be nice to save and restore the current selection in
510         //availableLV. Currently, we get an automatic reset, since the
511         //model is reset.
512
513         updateControls(bi);
514 }
515
516
517 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
518 {
519         findText(filter_->text(), true);
520 }
521
522
523 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
524 {
525         findText(filter_->text(), true);
526 }
527
528
529 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
530 {
531         if (index >= 0 && index < citationStyleCO->count()) {
532                 vector<CitationStyle> const & styles = citeStyles_;
533                 updateFormatting(styles[index]);
534                 changed();
535         }
536 }
537
538
539 void GuiCitation::filterChanged(const QString & text)
540 {
541         if (!text.isEmpty()) {
542                 if (instant_->isChecked())
543                         findText(filter_->text());
544                 return;
545         }
546         findText(filter_->text());
547         filter_->setFocus();
548 }
549
550
551 void GuiCitation::filterPressed()
552 {
553         findText(filter_->text(), true);
554 }
555
556
557 void GuiCitation::resetFilter()
558 {
559         filter_->setText(QString());
560         findText(filter_->text(), true);
561 }
562
563
564 void GuiCitation::caseChanged()
565 {
566         findText(filter_->text());
567 }
568
569
570 void GuiCitation::regexChanged()
571 {
572         findText(filter_->text());
573 }
574
575
576 void GuiCitation::updateFilterHint()
577 {
578         QString hint = instant_->isChecked() ?
579                 qt_("Enter string to filter the list of available citations") :
580                 qt_("Enter string to filter the list of available citations and press <Enter>");
581         hint += qt_("\nThe down arrow key will get you into the list of filtered citations.");
582         filter_->setToolTip(hint);
583 }
584
585
586 void GuiCitation::instantChanged(bool checked)
587 {
588         if (checked)
589                 findText(filter_->text(), true);
590
591         updateFilterHint();
592 }
593
594
595 void GuiCitation::changed()
596 {
597         setButtons();
598 }
599
600
601 void GuiCitation::applyParams(int const choice, bool full, bool force,
602         QString before, QString after)
603 {
604         if (cited_keys_.isEmpty())
605                 return;
606
607         vector<CitationStyle> const & styles = citeStyles_;
608
609         CitationStyle cs = styles[choice];
610
611         if (!cs.textBefore)
612                 before.clear();
613         if (!cs.textAfter)
614                 after.clear();
615
616         cs.forceUpperCase &= force;
617         cs.hasStarredVersion &= full;
618         string const command = citationStyleToString(cs);
619
620         params_.setCmdName(command);
621         params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
622         params_["before"] = qstring_to_ucs4(before);
623         params_["after"] = qstring_to_ucs4(after);
624         if (cs.hasQualifiedList) {
625                 params_["pretextlist"] = getStringFromVector(getPreTexts(), from_ascii("\t"));
626                 params_["posttextlist"] = getStringFromVector(getPostTexts(), from_ascii("\t"));
627         }
628         params_["literal"] = literalCB->isChecked() ? from_ascii("true") : from_ascii("false");
629         dispatchParams();
630 }
631
632
633 void GuiCitation::clearSelection()
634 {
635         cited_keys_.clear();
636         setSelectedKeys(cited_keys_);
637 }
638
639
640 void GuiCitation::setSelectedKeys(QStringList const sl)
641 {
642         selected_model_.clear();
643         selected_model_.setColumnCount(3);
644         QStringList headers;
645         headers << qt_("Text before")
646                 << qt_("Cite key")
647                 << qt_("Text after");
648         selected_model_.setHorizontalHeaderLabels(headers);
649         selectedLV->setColumnHidden(0, true);
650         selectedLV->setColumnHidden(2, true);
651         selectedLV->verticalHeader()->setVisible(false);
652         selectedLV->horizontalHeader()->setVisible(false);
653         QStringList::const_iterator it  = sl.begin();
654         QStringList::const_iterator end = sl.end();
655         for (int i = 0; it != end; ++it, ++i) {
656                 QStandardItem * si = new QStandardItem();
657                 si->setData(*it);
658                 si->setText(*it);
659                 si->setToolTip(*it);
660                 si->setEditable(false);
661                 selected_model_.setItem(i, 1, si);
662         }
663 }
664
665
666 QStringList GuiCitation::selectedKeys()
667 {
668         QStringList res;
669         for (int i = 0; i != selected_model_.rowCount(); ++i) {
670                 QStandardItem const * item = selected_model_.item(i, 1);
671                 if (item)
672                         res.append(item->text());
673         }
674         return res;
675 }
676
677
678 void GuiCitation::setPreTexts(vector<docstring> const m)
679 {
680         for (docstring const & s: m) {
681                 QStandardItem * si = new QStandardItem();
682                 docstring key;
683                 docstring pre = split(s, key, ' ');
684                 si->setData(toqstr(pre));
685                 si->setText(toqstr(pre));
686                 QModelIndexList qmil =
687                                 selected_model_.match(selected_model_.index(0, 1),
688                                                      Qt::DisplayRole, toqstr(key), 1,
689                                                      Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
690                 if (!qmil.empty())
691                         selected_model_.setItem(qmil.front().row(), 0, si);
692         }
693 }
694
695
696 vector<docstring> GuiCitation::getPreTexts()
697 {
698         vector<docstring> res;
699         for (int i = 0; i != selected_model_.rowCount(); ++i) {
700                 QStandardItem const * key = selected_model_.item(i, 1);
701                 QStandardItem const * pre = selected_model_.item(i, 0);
702                 if (key && pre && !key->text().isEmpty() && !pre->text().isEmpty())
703                         res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(pre->text()));
704         }
705         return res;
706 }
707
708
709 void GuiCitation::setPostTexts(vector<docstring> const m)
710 {
711         for (docstring const & s: m) {
712                 QStandardItem * si = new QStandardItem();
713                 docstring key;
714                 docstring post = split(s, key, ' ');
715                 si->setData(toqstr(post));
716                 si->setText(toqstr(post));
717                 QModelIndexList qmil =
718                                 selected_model_.match(selected_model_.index(0, 1),
719                                                      Qt::DisplayRole, toqstr(key), 1,
720                                                      Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
721                 if (!qmil.empty())
722                         selected_model_.setItem(qmil.front().row(), 2, si);
723         }
724 }
725
726
727 vector<docstring> GuiCitation::getPostTexts()
728 {
729         vector<docstring> res;
730         for (int i = 0; i != selected_model_.rowCount(); ++i) {
731                 QStandardItem const * key = selected_model_.item(i, 1);
732                 QStandardItem const * post = selected_model_.item(i, 2);
733                 if (key && post)
734                         res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(post->text()));
735         }
736         return res;
737 }
738
739
740 void GuiCitation::init()
741 {
742         // Make the list of all available bibliography keys
743         BiblioInfo const & bi = bibInfo();
744         all_keys_ = to_qstring_list(bi.getKeys());
745
746         available_model_.setStringList(all_keys_);
747
748         // Ditto for the keys cited in this inset
749         QString str = toqstr(params_["key"]);
750         if (str.isEmpty())
751                 cited_keys_.clear();
752         else
753                 cited_keys_ = str.split(",");
754         setSelectedKeys(cited_keys_);
755
756         // Initialize the drop downs
757         fillEntries(bi);
758         fillFields(bi);
759
760         // Initialize the citation formatting
761         string const & cmd = params_.getCmdName();
762         CitationStyle const cs =
763                 citationStyleFromString(cmd, documentBuffer().params());
764
765         forceuppercaseCB->setChecked(cs.forceUpperCase);
766         starredCB->setChecked(cs.hasStarredVersion &&
767                 documentBuffer().params().fullAuthorList());
768         textBeforeED->setText(toqstr(params_["before"]));
769         textAfterED->setText(toqstr(params_["after"]));
770
771         // if this is a new citation, we set the literal checkbox
772         // to its last set value.
773         if (cited_keys_.isEmpty())
774                 literalCB->setChecked(InsetCitation::last_literal);
775         else
776                 literalCB->setChecked(params_["literal"] == "true");
777
778         setPreTexts(getVectorFromString(params_["pretextlist"], from_ascii("\t")));
779         setPostTexts(getVectorFromString(params_["posttextlist"], from_ascii("\t")));
780
781         // Update the interface
782         updateControls(bi);
783         updateStyles(bi);
784         if (selected_model_.rowCount()) {
785                 selectedLV->blockSignals(true);
786                 selectedLV->setFocus();
787                 selectedLV->selectRow(0);
788                 selectedLV->blockSignals(false);
789
790                 // Find the citation style
791                 vector<string> const & cmds = citeCmds_;
792                 vector<string>::const_iterator cit =
793                         std::find(cmds.begin(), cmds.end(), cs.name);
794                 int i = 0;
795                 if (cit != cmds.end())
796                         i = int(cit - cmds.begin());
797
798                 // Set the style combo appropriately
799                 citationStyleCO->blockSignals(true);
800                 citationStyleCO->setCurrentIndex(i);
801                 citationStyleCO->blockSignals(false);
802                 updateFormatting(citeStyles_[i]);
803         } else
804                 availableLV->setFocus();
805
806         applyPB->setEnabled(false);
807         okPB->setEnabled(false);
808 }
809
810
811 void GuiCitation::findKey(BiblioInfo const & bi,
812         QString const & str, bool only_keys,
813         docstring field, docstring entry_type,
814         bool case_sensitive, bool reg_exp, bool reset)
815 {
816         // FIXME THREAD
817         // This should be moved to a class member.
818         // Used for optimisation: store last searched string.
819         static QString last_searched_string;
820         // Used to disable the above optimisation.
821         static bool last_case_sensitive;
822         static bool last_reg_exp;
823         // Reset last_searched_string in case of changed option.
824         if (last_case_sensitive != case_sensitive
825                 || last_reg_exp != reg_exp) {
826                         LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
827                 last_searched_string.clear();
828         }
829         // save option for next search.
830         last_case_sensitive = case_sensitive;
831         last_reg_exp = reg_exp;
832
833         Qt::CaseSensitivity qtcase = case_sensitive ?
834                         Qt::CaseSensitive: Qt::CaseInsensitive;
835         QStringList keys;
836         // If new string (str) contains the last searched one...
837         if (!reset &&
838                 !last_searched_string.isEmpty() &&
839                 str.size() > 1 &&
840                 str.contains(last_searched_string, qtcase))
841                 // ... then only search within already found list.
842                 keys = available_model_.stringList();
843         else
844                 // ... else search all keys.
845                 keys = all_keys_;
846         // save searched string for next search.
847         last_searched_string = str;
848
849         QStringList result;
850
851         // First, filter by entry_type, which will be faster than
852         // what follows, so we may get to do that on less.
853         vector<docstring> keyVector = to_docstring_vector(keys);
854         filterByEntryType(bi, keyVector, entry_type);
855
856         if (str.isEmpty())
857                 result = to_qstring_list(keyVector);
858         else
859                 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
860                         qstring_to_ucs4(str), field, case_sensitive, reg_exp));
861
862         available_model_.setStringList(result);
863 }
864
865
866 BiblioInfo::CiteStringMap GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
867 {
868         vector<docstring> const keys = to_docstring_vector(cited_keys_);
869         vector<CitationStyle> styles = citeStyles_;
870         int ind = citationStyleCO->currentIndex();
871         if (ind == -1)
872                 ind = 0;
873         CitationStyle cs = styles[ind];
874         vector<docstring> pretexts = getPreTexts();
875         vector<docstring> posttexts = getPostTexts();
876         bool const qualified = cs.hasQualifiedList
877                 && (selectedLV->model()->rowCount() > 1
878                     || !pretexts.empty()
879                     || !posttexts.empty());
880         std::map<docstring, docstring> pres;
881         for (docstring const & s: pretexts) {
882                 docstring key;
883                 docstring val = split(s, key, ' ');
884                 pres[key] = val;
885         }
886         std::map<docstring, docstring> posts;
887         for (docstring const & s: posttexts) {
888                 docstring key;
889                 docstring val = split(s, key, ' ');
890                 posts[key] = val;
891         }
892         CiteItem ci;
893         ci.textBefore = qstring_to_ucs4(textBeforeED->text());
894         ci.textAfter = qstring_to_ucs4(textAfterED->text());
895         ci.forceUpperCase = forceuppercaseCB->isChecked();
896         ci.Starred = starredCB->isChecked();
897         ci.context = CiteItem::Dialog;
898         ci.max_size = max_size;
899         ci.isQualified = qualified;
900         ci.pretexts = pres;
901         ci.posttexts = posts;
902         BiblioInfo::CiteStringMap ret = bi.getCiteStrings(keys, styles, documentBuffer(), ci);
903         return ret;
904 }
905
906
907 void GuiCitation::setCitedKeys()
908 {
909         cited_keys_ = selectedKeys();
910         updateStyles();
911 }
912
913
914 bool GuiCitation::initialiseParams(string const & data)
915 {
916         InsetCommand::string2params(data, params_);
917         citeCmds_ = documentBuffer().params().citeCommands();
918         citeStyles_ = documentBuffer().params().citeStyles();
919         init();
920         return true;
921 }
922
923
924 void GuiCitation::clearParams()
925 {
926         params_.clear();
927 }
928
929
930 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
931         vector<docstring> & keyVector, docstring entry_type)
932 {
933         if (entry_type.empty())
934                 return;
935
936         vector<docstring>::iterator it = keyVector.begin();
937         vector<docstring>::iterator end = keyVector.end();
938
939         vector<docstring> result;
940         for (; it != end; ++it) {
941                 docstring const key = *it;
942                 BiblioInfo::const_iterator cit = bi.find(key);
943                 if (cit == bi.end())
944                         continue;
945                 if (cit->second.entryType() == entry_type)
946                         result.push_back(key);
947         }
948         keyVector = result;
949 }
950
951
952 // Escape special chars.
953 // All characters are literals except: '.|*?+(){}[]^$\'
954 // These characters are literals when preceded by a "\", which is done here
955 // @todo: This function should be moved to support, and then the test in tests
956 //        should be moved there as well.
957 static docstring escape_special_chars(docstring const & expr)
958 {
959         // Search for all chars '.|*?+(){}[^$]\'
960         // Note that '[', ']', and '\' must be escaped.
961         static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
962
963         // $& is an ECMAScript format expression that expands to all
964         // of the current match
965 #ifdef LYX_USE_STD_REGEX
966         // To prefix a matched expression with a single literal backslash, we
967         // need to escape it for the C++ compiler and use:
968         // FIXME: UNICODE
969         return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
970 #else
971         // A backslash in the format string starts an escape sequence in boost.
972         // Thus, to prefix a matched expression with a single literal backslash,
973         // we need to give two backslashes to the regex engine, and escape both
974         // for the C++ compiler and use:
975         // FIXME: UNICODE
976         return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
977 #endif
978 }
979
980
981 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
982         vector<docstring> const & keys_to_search, bool only_keys,
983         docstring const & search_expression, docstring field,
984         bool case_sensitive, bool regex)
985 {
986         vector<docstring> foundKeys;
987
988         docstring expr = trim(search_expression);
989         if (expr.empty())
990                 return foundKeys;
991
992         if (!regex)
993                 // We must escape special chars in the search_expr so that
994                 // it is treated as a simple string by lyx::regex.
995                 expr = escape_special_chars(expr);
996
997         lyx::regex reg_exp;
998         try {
999                 reg_exp.assign(to_utf8(expr), case_sensitive ?
1000                         lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
1001         } catch (lyx::regex_error const & e) {
1002                 // lyx::regex throws an exception if the regular expression is not
1003                 // valid.
1004                 LYXERR(Debug::GUI, e.what());
1005                 return vector<docstring>();
1006         }
1007
1008         vector<docstring>::const_iterator it = keys_to_search.begin();
1009         vector<docstring>::const_iterator end = keys_to_search.end();
1010         for (; it != end; ++it ) {
1011                 BiblioInfo::const_iterator info = bi.find(*it);
1012                 if (info == bi.end())
1013                         continue;
1014
1015                 BibTeXInfo const & kvm = info->second;
1016                 string data;
1017                 if (only_keys)
1018                         data = to_utf8(*it);
1019                 else if (field.empty())
1020                         data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
1021                 else
1022                         data = to_utf8(kvm[field]);
1023
1024                 if (data.empty())
1025                         continue;
1026
1027                 try {
1028                         if (lyx::regex_search(data, reg_exp))
1029                                 foundKeys.push_back(*it);
1030                 }
1031                 catch (lyx::regex_error const & e) {
1032                         LYXERR(Debug::GUI, e.what());
1033                         return vector<docstring>();
1034                 }
1035         }
1036         return foundKeys;
1037 }
1038
1039
1040 void GuiCitation::dispatchParams()
1041 {
1042         std::string const lfun = InsetCommand::params2string(params_);
1043         dispatch(FuncRequest(getLfun(), lfun));
1044 }
1045
1046
1047 BiblioInfo const & GuiCitation::bibInfo() const
1048 {
1049         Buffer const & buf = documentBuffer();
1050         buf.reloadBibInfoCache();
1051         return buf.masterBibInfo();
1052 }
1053
1054
1055 void GuiCitation::saveSession(QSettings & settings) const
1056 {
1057         Dialog::saveSession(settings);
1058         settings.setValue(
1059                 sessionKey() + "/regex", regexp_->isChecked());
1060         settings.setValue(
1061                 sessionKey() + "/casesensitive", casesense_->isChecked());
1062         settings.setValue(
1063                 sessionKey() + "/autofind", instant_->isChecked());
1064         settings.setValue(
1065                 sessionKey() + "/citestyle", style_);
1066         settings.setValue(
1067                 sessionKey() + "/literal", InsetCitation::last_literal);
1068 }
1069
1070
1071 void GuiCitation::restoreSession()
1072 {
1073         Dialog::restoreSession();
1074         QSettings settings;
1075         regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
1076         casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
1077         instant_->setChecked(settings.value(sessionKey() + "/autofind", true).toBool());
1078         style_ = settings.value(sessionKey() + "/citestyle").toString();
1079         InsetCitation::last_literal = 
1080                 settings.value(sessionKey() + "/literal", false).toBool();
1081         updateFilterHint();
1082 }
1083
1084
1085 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
1086
1087
1088 } // namespace frontend
1089 } // namespace lyx
1090
1091 #include "moc_GuiCitation.cpp"
1092