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