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