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