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