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