3 * \file GuiCitation.cpp
4 * This file is part of LyX, the document processor.
5 * Licence details can be found in the file COPYING.
7 * \author Angus Leeming
8 * \author Kalle Dalheimer
9 * \author Abdelrazak Younes
10 * \author Richard Kimberly Heck
12 * Full author contact details are available in file CREDITS.
17 #include "GuiCitation.h"
19 #include "FancyLineEdit.h"
20 #include "GuiApplication.h"
21 #include "GuiSelectionManager.h"
23 #include "qt_helpers.h"
26 #include "BufferView.h"
27 #include "BufferParams.h"
30 #include "TextClass.h"
31 #include "FuncRequest.h"
33 #include "insets/InsetCitation.h"
34 #include "insets/InsetCommand.h"
36 #include "support/debug.h"
37 #include "support/docstring.h"
38 #include "support/gettext.h"
39 #include "support/lstrings.h"
41 #include <QCloseEvent>
45 #include <QStandardItemModel>
56 using namespace lyx::support;
62 // I am guessing that it would not hurt to make these private members.
63 static vector<string> citeCmds_;
64 static vector<CitationStyle> citeStyles_;
67 template<typename String>
68 static QStringList to_qstring_list(vector<String> const & v)
72 for (size_t i = 0; i != v.size(); ++i) {
75 qlist.append(lyx::toqstr(v[i]));
81 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
83 vector<lyx::docstring> v;
84 for (int i = 0; i != qlist.size(); ++i) {
85 if (qlist[i].isEmpty())
87 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
93 GuiCitation::GuiCitation(GuiView & lv)
94 : DialogView(lv, "citation", qt_("Citation")),
95 style_(QString()), params_(insetCode("citation"))
100 filter_ = new FancyLineEdit(this);
101 filter_->setClearButton(true);
102 filter_->setPlaceholderText(qt_("All avail. citations"));
104 filterBarL->addWidget(filter_, 0);
105 findKeysLA->setBuddy(filter_);
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);
116 QMenu * searchOpts = new QMenu(this);
117 searchOpts->addAction(regexp_);
118 searchOpts->addAction(casesense_);
119 searchOpts->addAction(instant_);
120 searchOptionsPB->setMenu(searchOpts);
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()));
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()));
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)));
165 selectedLV->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
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_);
173 void GuiCitation::closeEvent(QCloseEvent * e)
176 DialogView::closeEvent(e);
180 void GuiCitation::applyView()
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();
187 QString const before = textBeforeED->text();
188 QString const after = textAfterED->text();
190 applyParams(choice, full, force, before, after);
195 void GuiCitation::showEvent(QShowEvent * e)
197 if (!filter_->text().isEmpty())
199 availableLV->setFocus();
200 DialogView::showEvent(e);
204 void GuiCitation::on_buttonBox_accepted()
212 void GuiCitation::on_buttonBox_rejected()
219 void GuiCitation::on_buttonBox_clicked(QAbstractButton * button)
221 switch (buttonBox->standardButton(button)) {
222 case QDialogButtonBox::Apply:
225 case QDialogButtonBox::Reset:
236 void GuiCitation::on_literalCB_clicked()
238 InsetCitation::last_literal = literalCB->isChecked();
243 void GuiCitation::updateControls()
245 BiblioInfo const & bi = bibInfo();
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)
256 QModelIndex idx = selectionManager->getSelectedIndex(1);
258 int i = citationStyleCO->currentIndex();
259 if (i == -1 || i > int(citeStyles_.size()))
261 updateFormatting(citeStyles_[size_type(i)]);
262 selectionManager->update();
266 void GuiCitation::updateFormatting(CitationStyle const & currentStyle)
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;
275 int const rows = selectedLV->model()->rowCount();
277 bool const qualified = currentStyle.hasQualifiedList && rows > 0;
279 selectedLV->horizontalHeader()->setVisible(qualified);
280 selectedLV->setColumnHidden(0, !qualified);
281 selectedLV->setColumnHidden(2, !qualified);
282 bool const haveSelection = rows > 0;
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."));
294 textBeforeLA->setText(qt_("Text befo&re:"));
295 if (textbefore && haveSelection)
296 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\")"));
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)"));
304 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages), "
305 "if the current citation style supports this."));
308 forceuppercaseCB->setEnabled(force && haveSelection);
309 if (force && haveSelection)
310 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\")."));
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);
323 // Check if we have a custom string/tooltip for the starred version
324 if (starred && !currentStyle.stardesc.empty()) {
326 bp.documentClass().getCiteMacro(bp.citeEngineType(), currentStyle.stardesc);
329 guistring = translateIfPossible(from_utf8(val));
330 starredCB->setText(toqstr(guistring));
331 starredCB->setEnabled(haveSelection);
333 if (!currentStyle.startooltip.empty()) {
334 val = bp.documentClass().getCiteMacro(bp.citeEngineType(),
335 currentStyle.startooltip);
337 guistring = translateIfPossible(from_utf8(val));
339 // Tooltip might also be empty
340 starredCB->setToolTip(toqstr(guistring));
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.\")"));
347 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\"), "
348 "if the current citation style supports this."));
350 if (availableLV->selectionModel()->selectedIndexes().isEmpty())
351 availableLV->setToolTip(qt_("All references available for citing."));
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);
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()
366 BiblioInfo const & bi = bibInfo();
372 // Update the styles for the style combo, citationStyleCO.
373 void GuiCitation::updateStyles(BiblioInfo const & bi)
375 QStringList selected_keys = selectedKeys();
376 int curr = selectedLV->model()->rowCount() - 1;
378 if (curr < 0 || selected_keys.empty()) {
380 citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
381 citationStyleCO->clear();
382 citationStyleCO->setEnabled(false);
383 citationStyleLA->setEnabled(false);
387 static const size_t max_length = 80;
388 BiblioInfo::CiteStringMap sty = citationStyles(bi, max_length);
392 citationStyleCO->setEnabled(false);
393 citationStyleLA->setEnabled(false);
394 citationStyleCO->clear();
398 citationStyleCO->blockSignals(true);
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;
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);
417 citationStyleCO->setCurrentIndex(i);
419 citationStyleCO->blockSignals(false);
423 void GuiCitation::fillFields(BiblioInfo const & bi)
425 fieldsCO->blockSignals(true);
426 int const oldIndex = fieldsCO->currentIndex();
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);
438 void GuiCitation::fillEntries(BiblioInfo const & bi)
440 entriesCO->blockSignals(true);
441 int const oldIndex = entriesCO->currentIndex();
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);
452 bool GuiCitation::isSelected(QModelIndex const & idx)
454 QString const str = idx.data().toString();
455 return selectedKeys().contains(str);
459 void GuiCitation::setButtons()
461 int const srows = selectedLV->model()->rowCount();
462 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(srows > 0);
463 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(srows > 0);
467 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
469 if (!idx.isValid() || bi.empty()) {
470 infoML->document()->clear();
471 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
475 infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
478 QString const keytxt = toqstr(
479 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), ci));
480 infoML->document()->setHtml(keytxt);
484 void GuiCitation::findText(QString const & text, bool reset)
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();
492 if (index <= -1 || index >= int(fields.size()))
493 //either "All Fields" or "Keys" or an invalid value
494 field = from_ascii("");
496 field = fields[size_type(index)];
499 bool const onlyKeys = index == -1;
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("");
508 entry_type = entries[size_type(index)];
510 bool const case_sentitive = casesense_->isChecked();
511 bool const reg_exp = regexp_->isChecked();
513 findKey(bi, text, onlyKeys, field, entry_type,
514 case_sentitive, reg_exp, reset);
516 //It'd be nice to save and restore the current selection in
517 //availableLV. Currently, we get an automatic reset, since the
524 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
526 findText(filter_->text(), true);
530 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
532 findText(filter_->text(), true);
536 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
538 if (index >= 0 && index < citationStyleCO->count()) {
539 vector<CitationStyle> const & styles = citeStyles_;
540 updateFormatting(styles[size_type(index)]);
546 void GuiCitation::filterChanged(const QString & text)
548 if (!text.isEmpty()) {
549 if (instant_->isChecked())
550 findText(filter_->text());
553 findText(filter_->text());
558 void GuiCitation::filterPressed()
560 findText(filter_->text(), true);
564 void GuiCitation::resetFilter()
566 filter_->setText(QString());
567 findText(filter_->text(), true);
571 void GuiCitation::caseChanged()
573 findText(filter_->text());
577 void GuiCitation::regexChanged()
579 findText(filter_->text());
583 void GuiCitation::updateFilterHint()
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);
593 void GuiCitation::instantChanged(bool checked)
596 findText(filter_->text(), true);
602 void GuiCitation::changed()
608 void GuiCitation::applyParams(int const choice, bool full, bool force,
609 QString before, QString after)
611 if (cited_keys_.isEmpty())
614 vector<CitationStyle> const & styles = citeStyles_;
616 CitationStyle cs = styles[size_type(choice)];
623 cs.forceUpperCase &= force;
624 cs.hasStarredVersion &= full;
625 string const command = citationStyleToString(cs);
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"));
635 params_["literal"] = literalCB->isChecked() ? from_ascii("true") : from_ascii("false");
640 void GuiCitation::clearSelection()
643 setSelectedKeys(cited_keys_);
647 void GuiCitation::setSelectedKeys(QStringList const & sl)
649 selected_model_.clear();
650 selected_model_.setColumnCount(3);
652 headers << qt_("Text before")
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();
667 si->setEditable(false);
668 selected_model_.setItem(i, 1, si);
673 QStringList GuiCitation::selectedKeys()
676 for (int i = 0; i != selected_model_.rowCount(); ++i) {
677 QStandardItem const * item = selected_model_.item(i, 1);
679 res.append(item->text());
685 void GuiCitation::setPreTexts(vector<docstring> const & m)
687 // account for multiple use of the same keys
688 QList<QModelIndex> handled;
689 for (docstring const & s: m) {
690 QStandardItem * si = new QStandardItem();
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);
710 vector<docstring> GuiCitation::getPreTexts()
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()));
723 void GuiCitation::setPostTexts(vector<docstring> const & m)
725 // account for multiple use of the same keys
726 QList<QModelIndex> handled;
727 for (docstring const & s: m) {
728 QStandardItem * si = new QStandardItem();
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);
748 vector<docstring> GuiCitation::getPostTexts()
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()));
761 void GuiCitation::init()
763 // Make the list of all available bibliography keys
764 BiblioInfo const & bi = bibInfo();
765 all_keys_ = to_qstring_list(bi.getKeys());
767 available_model_.setStringList(all_keys_);
769 // Ditto for the keys cited in this inset
770 QString str = toqstr(params_["key"]);
774 cited_keys_ = str.split(",");
775 setSelectedKeys(cited_keys_);
777 // Initialize the drop downs
781 // Initialize the citation formatting
782 string const & cmd = params_.getCmdName();
783 CitationStyle const cs =
784 citationStyleFromString(cmd, documentBuffer().params());
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"]));
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);
797 literalCB->setChecked(params_["literal"] == "true");
799 setPreTexts(getVectorFromString(params_["pretextlist"], from_ascii("\t")));
800 setPostTexts(getVectorFromString(params_["posttextlist"], from_ascii("\t")));
802 // Update the interface
805 if (selected_model_.rowCount()) {
806 selectedLV->blockSignals(true);
807 selectedLV->setFocus();
808 selectedLV->selectRow(0);
809 selectedLV->blockSignals(false);
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);
816 if (cit != cmds.end())
817 i = int(cit - cmds.begin());
819 // Set the style combo appropriately
820 citationStyleCO->blockSignals(true);
821 citationStyleCO->setCurrentIndex(i);
822 citationStyleCO->blockSignals(false);
823 updateFormatting(citeStyles_[size_type(i)]);
825 availableLV->setFocus();
827 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
828 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
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)
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();
850 // save option for next search.
851 last_case_sensitive = case_sensitive;
852 last_reg_exp = reg_exp;
854 Qt::CaseSensitivity qtcase = case_sensitive ?
855 Qt::CaseSensitive: Qt::CaseInsensitive;
857 // If new string (str) contains the last searched one...
859 !last_searched_string.isEmpty() &&
861 str.contains(last_searched_string, qtcase))
862 // ... then only search within already found list.
863 keys = available_model_.stringList();
865 // ... else search all keys.
867 // save searched string for next search.
868 last_searched_string = str;
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);
878 result = to_qstring_list(keyVector);
880 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
881 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
883 available_model_.setStringList(result);
887 BiblioInfo::CiteStringMap GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
889 vector<docstring> const keys = to_docstring_vector(cited_keys_);
890 vector<CitationStyle> styles = citeStyles_;
891 int ind = citationStyleCO->currentIndex();
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
900 || !posttexts.empty());
901 vector<pair<docstring, docstring>> pres;
902 for (docstring const & s: pretexts) {
904 docstring val = split(s, key, ' ');
905 pres.push_back(make_pair(key, val));
907 vector<pair<docstring, docstring>> posts;
908 for (docstring const & s: posttexts) {
910 docstring val = split(s, key, ' ');
911 posts.push_back(make_pair(key, val));
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;
922 ci.posttexts = posts;
923 BiblioInfo::CiteStringMap ret = bi.getCiteStrings(keys, styles, documentBuffer(), ci);
928 void GuiCitation::setCitedKeys()
930 cited_keys_ = selectedKeys();
935 bool GuiCitation::initialiseParams(string const & sdata)
937 InsetCommand::string2params(sdata, params_);
938 citeCmds_ = documentBuffer().params().citeCommands();
939 citeStyles_ = documentBuffer().params().citeStyles();
945 void GuiCitation::clearParams()
951 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
952 vector<docstring> & keyVector, docstring const & entry_type)
954 if (entry_type.empty())
957 vector<docstring>::iterator it = keyVector.begin();
958 vector<docstring>::iterator end = keyVector.end();
960 vector<docstring> result;
961 for (; it != end; ++it) {
962 docstring const key = *it;
963 BiblioInfo::const_iterator cit = bi.find(key);
966 if (cit->second.entryType() == entry_type)
967 result.push_back(key);
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)
980 // Search for all chars '.|*?+(){}[^$]\'
981 // Note that '[', ']', and '\' must be escaped.
982 static const regex reg("[.|*?+(){}^$\\[\\]\\\\]");
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:
989 return from_utf8(regex_replace(to_utf8(expr), reg, string("\\$&")));
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)
998 vector<docstring> foundKeys;
1000 docstring expr = trim(search_expression);
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);
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
1016 LYXERR(Debug::GUI, e.what());
1017 return vector<docstring>();
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())
1027 BibTeXInfo const & kvm = info->second;
1030 sdata = to_utf8(*it);
1031 else if (field.empty())
1032 sdata = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
1034 sdata = to_utf8(kvm[field]);
1040 if (regex_search(sdata, reg_exp))
1041 foundKeys.push_back(*it);
1043 catch (regex_error const & e) {
1044 LYXERR(Debug::GUI, e.what());
1045 return vector<docstring>();
1052 void GuiCitation::dispatchParams()
1054 std::string const lfun = InsetCommand::params2string(params_);
1055 dispatch(FuncRequest(getLfun(), lfun));
1059 BiblioInfo const & GuiCitation::bibInfo() const
1061 Buffer const & buf = documentBuffer();
1062 buf.reloadBibInfoCache();
1063 return buf.masterBibInfo();
1067 void GuiCitation::saveSession(QSettings & settings) const
1069 Dialog::saveSession(settings);
1071 sessionKey() + "/regex", regexp_->isChecked());
1073 sessionKey() + "/casesensitive", casesense_->isChecked());
1075 sessionKey() + "/autofind", instant_->isChecked());
1077 sessionKey() + "/citestyle", style_);
1079 sessionKey() + "/literal", InsetCitation::last_literal);
1083 void GuiCitation::restoreSession()
1085 Dialog::restoreSession();
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();
1097 } // namespace frontend
1100 #include "moc_GuiCitation.cpp"