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 #if (QT_VERSION < 0x050000)
157 connect(filter_, SIGNAL(downPressed()),
158 availableLV, SLOT(setFocus()));
160 connect(filter_, &FancyLineEdit::downPressed,
161 availableLV, [this](){ focusAndHighlight(availableLV); });
163 connect(regexp_, SIGNAL(triggered()),
164 this, SLOT(regexChanged()));
165 connect(casesense_, SIGNAL(triggered()),
166 this, SLOT(caseChanged()));
167 connect(instant_, SIGNAL(triggered(bool)),
168 this, SLOT(instantChanged(bool)));
170 #if (QT_VERSION < 0x050000)
171 selectedLV->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
173 selectedLV->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
176 selectedLV->setToolTip(qt_("Ordered list of all cited references.\n"
177 "You can reorder, add and remove references with the buttons on the left."));
178 setFocusProxy(filter_);
182 void GuiCitation::closeEvent(QCloseEvent * e)
185 DialogView::closeEvent(e);
189 void GuiCitation::applyView()
191 int const choice = max(0, citationStyleCO->currentIndex());
192 style_ = citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
193 bool const full = starredCB->isChecked();
194 bool const force = forceuppercaseCB->isChecked();
196 QString const before = textBeforeED->text();
197 QString const after = textAfterED->text();
199 applyParams(choice, full, force, before, after);
204 void GuiCitation::showEvent(QShowEvent * e)
206 if (!filter_->text().isEmpty())
208 availableLV->setFocus();
209 DialogView::showEvent(e);
213 void GuiCitation::on_buttonBox_accepted()
221 void GuiCitation::on_buttonBox_rejected()
228 void GuiCitation::on_buttonBox_clicked(QAbstractButton * button)
230 switch (buttonBox->standardButton(button)) {
231 case QDialogButtonBox::Apply:
234 case QDialogButtonBox::Reset:
245 void GuiCitation::on_literalCB_clicked()
247 InsetCitation::last_literal = literalCB->isChecked();
252 void GuiCitation::updateControls()
254 BiblioInfo const & bi = bibInfo();
259 // The main point of separating this out is that the fill*() methods
260 // called in update() do not need to be called for INTERNAL updates,
261 // such as when addPB is pressed, as the list of fields, entries, etc,
262 // will not have changed.
263 void GuiCitation::updateControls(BiblioInfo const & bi)
265 QModelIndex idx = selectionManager->getSelectedIndex(1);
267 int i = citationStyleCO->currentIndex();
268 if (i == -1 || i > int(citeStyles_.size()))
270 updateFormatting(citeStyles_[size_type(i)]);
271 selectionManager->update();
275 void GuiCitation::updateFormatting(CitationStyle const & currentStyle)
277 BufferParams const bp = documentBuffer().params();
278 bool const force = currentStyle.forceUpperCase;
279 bool const starred = currentStyle.hasStarredVersion;
280 bool const full = starred && bp.fullAuthorList();
281 bool const textbefore = currentStyle.textBefore;
282 bool const textafter = currentStyle.textAfter;
284 int const rows = selectedLV->model()->rowCount();
286 bool const qualified = currentStyle.hasQualifiedList && rows > 0;
288 selectedLV->horizontalHeader()->setVisible(qualified);
289 selectedLV->setColumnHidden(0, !qualified);
290 selectedLV->setColumnHidden(2, !qualified);
291 bool const haveSelection = rows > 0;
293 textBeforeLA->setText(qt_("General text befo&re:"));
294 textAfterLA->setText(qt_("General &text after:"));
295 textBeforeED->setToolTip(qt_("Text that precedes the whole reference list. "
296 "For text that precedes individual items, "
297 "double-click on the respective entry above."));
298 textAfterLA->setToolTip(qt_("General &text after:"));
299 textAfterED->setToolTip(qt_("Text that follows the whole reference list. "
300 "For text that follows individual items, "
301 "double-click on the respective entry above."));
303 textBeforeLA->setText(qt_("Text befo&re:"));
304 if (textbefore && haveSelection)
305 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\")"));
307 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\"), "
308 "if the current citation style supports this."));
309 textAfterLA->setText(qt_("&Text after:"));
310 if (textafter && haveSelection)
311 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages)"));
313 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages), "
314 "if the current citation style supports this."));
317 forceuppercaseCB->setEnabled(force && haveSelection);
318 if (force && haveSelection)
319 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\")."));
321 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\"), "
322 "if the current citation style supports this."));
323 starredCB->setEnabled(full && haveSelection);
324 textBeforeED->setEnabled(textbefore && haveSelection);
325 textBeforeLA->setEnabled(textbefore && haveSelection);
326 textAfterED->setEnabled(textafter && haveSelection);
327 textAfterLA->setEnabled(textafter && haveSelection);
328 literalCB->setEnabled(textbefore || textafter);
329 citationStyleCO->setEnabled(haveSelection);
330 citationStyleLA->setEnabled(haveSelection);
332 // Check if we have a custom string/tooltip for the starred version
333 if (starred && !currentStyle.stardesc.empty()) {
335 bp.documentClass().getCiteMacro(bp.citeEngineType(), currentStyle.stardesc);
338 guistring = translateIfPossible(from_utf8(val));
339 starredCB->setText(toqstr(guistring));
340 starredCB->setEnabled(haveSelection);
342 if (!currentStyle.startooltip.empty()) {
343 val = bp.documentClass().getCiteMacro(bp.citeEngineType(),
344 currentStyle.startooltip);
346 guistring = translateIfPossible(from_utf8(val));
348 // Tooltip might also be empty
349 starredCB->setToolTip(toqstr(guistring));
351 // This is the default meaning of the starred commands
352 starredCB->setText(qt_("All aut&hors"));
353 if (full && haveSelection)
354 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\")"));
356 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\"), "
357 "if the current citation style supports this."));
359 if (availableLV->selectionModel()->selectedIndexes().isEmpty())
360 availableLV->setToolTip(qt_("All references available for citing."));
362 availableLV->setToolTip(qt_("All references available for citing.\n"
363 "To add the selected one, hit Add, press Enter or double-click.\n"
364 "Hit Ctrl-Enter to add and close the dialog."));
365 // With qualified citation lists, it makes sense to add the same key multiple times
366 selectionManager->allowMultiSelection(currentStyle.hasQualifiedList);
370 // Update the styles for the style combo, citationStyleCO, and mark the
371 // settings as changed. Called upon changing the cited keys (including
372 // merely reordering the keys) or editing the text before/after fields.
373 void GuiCitation::updateStyles()
375 BiblioInfo const & bi = bibInfo();
381 // Update the styles for the style combo, citationStyleCO.
382 void GuiCitation::updateStyles(BiblioInfo const & bi)
384 QStringList selected_keys = selectedKeys();
385 int curr = selectedLV->model()->rowCount() - 1;
387 if (curr < 0 || selected_keys.empty()) {
389 citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
390 citationStyleCO->clear();
391 citationStyleCO->setEnabled(false);
392 citationStyleLA->setEnabled(false);
396 static const size_t max_length = 80;
397 BiblioInfo::CiteStringMap sty = citationStyles(bi, max_length);
401 citationStyleCO->setEnabled(false);
402 citationStyleLA->setEnabled(false);
403 citationStyleCO->clear();
407 citationStyleCO->blockSignals(true);
409 // save old style selection
410 QString const curdata =
411 citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
412 QString const olddata = (curdata.isEmpty()) ?
413 (last_chosen_style_.isEmpty() ? style_ : last_chosen_style_): curdata;
415 last_chosen_style_.clear();
416 citationStyleCO->clear();
417 BiblioInfo::CiteStringMap::const_iterator cit = sty.begin();
418 BiblioInfo::CiteStringMap::const_iterator end = sty.end();
419 for (int ii = 1; cit != end; ++cit, ++ii)
420 citationStyleCO->addItem(toqstr(cit->second), toqstr(cit->first));
421 citationStyleCO->setEnabled(true);
422 citationStyleLA->setEnabled(true);
423 // restore old style selection
424 int const i = citationStyleCO->findData(olddata);
426 citationStyleCO->setCurrentIndex(i);
428 citationStyleCO->blockSignals(false);
432 void GuiCitation::fillFields(BiblioInfo const & bi)
434 fieldsCO->blockSignals(true);
435 int const oldIndex = fieldsCO->currentIndex();
437 QStringList const fields = to_qstring_list(bi.getFields());
438 fieldsCO->insertItem(0, qt_("All fields"));
439 fieldsCO->insertItem(1, qt_("Keys"));
440 fieldsCO->insertItems(2, fields);
441 if (oldIndex != -1 && oldIndex < fieldsCO->count())
442 fieldsCO->setCurrentIndex(oldIndex);
443 fieldsCO->blockSignals(false);
447 void GuiCitation::fillEntries(BiblioInfo const & bi)
449 entriesCO->blockSignals(true);
450 int const oldIndex = entriesCO->currentIndex();
452 QStringList const entries = to_qstring_list(bi.getEntries());
453 entriesCO->insertItem(0, qt_("All entry types"));
454 entriesCO->insertItems(1, entries);
455 if (oldIndex != -1 && oldIndex < entriesCO->count())
456 entriesCO->setCurrentIndex(oldIndex);
457 entriesCO->blockSignals(false);
461 bool GuiCitation::isSelected(QModelIndex const & idx)
463 QString const str = idx.data().toString();
464 return selectedKeys().contains(str);
468 void GuiCitation::setButtons()
470 int const srows = selectedLV->model()->rowCount();
471 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(srows > 0);
472 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(srows > 0);
476 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
478 if (!idx.isValid() || bi.empty()) {
479 infoML->document()->clear();
480 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
484 infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
487 QString const keytxt = toqstr(
488 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), ci));
489 infoML->document()->setHtml(keytxt);
493 void GuiCitation::findText(QString const & text, bool reset)
495 //"All Fields" and "Keys" are the first two
496 int index = fieldsCO->currentIndex() - 2;
497 BiblioInfo const & bi = bibInfo();
498 vector<docstring> const & fields = bi.getFields();
501 if (index <= -1 || index >= int(fields.size()))
502 //either "All Fields" or "Keys" or an invalid value
503 field = from_ascii("");
505 field = fields[size_type(index)];
508 bool const onlyKeys = index == -1;
510 //"All Entry Types" is first.
511 index = entriesCO->currentIndex() - 1;
512 vector<docstring> const & entries = bi.getEntries();
513 docstring entry_type;
514 if (index < 0 || index >= int(entries.size()))
515 entry_type = from_ascii("");
517 entry_type = entries[size_type(index)];
519 bool const case_sentitive = casesense_->isChecked();
520 bool const reg_exp = regexp_->isChecked();
522 findKey(bi, text, onlyKeys, field, entry_type,
523 case_sentitive, reg_exp, reset);
525 //It'd be nice to save and restore the current selection in
526 //availableLV. Currently, we get an automatic reset, since the
533 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
535 findText(filter_->text(), true);
539 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
541 findText(filter_->text(), true);
545 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
547 if (index >= 0 && index < citationStyleCO->count()) {
548 vector<CitationStyle> const & styles = citeStyles_;
549 updateFormatting(styles[size_type(index)]);
555 void GuiCitation::filterChanged(const QString & text)
557 if (!text.isEmpty()) {
558 if (instant_->isChecked())
559 findText(filter_->text());
562 findText(filter_->text());
567 void GuiCitation::filterPressed()
569 findText(filter_->text(), true);
573 void GuiCitation::resetFilter()
575 filter_->setText(QString());
576 findText(filter_->text(), true);
580 void GuiCitation::caseChanged()
582 findText(filter_->text());
586 void GuiCitation::regexChanged()
588 findText(filter_->text());
592 void GuiCitation::updateFilterHint()
594 QString hint = instant_->isChecked() ?
595 qt_("Enter string to filter the list of available citations") :
596 qt_("Enter string to filter the list of available citations and press <Enter>");
597 hint += qt_("\nThe down arrow key will get you into the list of filtered citations.");
598 filter_->setToolTip(hint);
602 void GuiCitation::instantChanged(bool checked)
605 findText(filter_->text(), true);
611 void GuiCitation::changed()
617 void GuiCitation::applyParams(int const choice, bool full, bool force,
618 QString before, QString after)
620 if (cited_keys_.isEmpty())
623 vector<CitationStyle> const & styles = citeStyles_;
625 CitationStyle cs = styles[size_type(choice)];
632 cs.forceUpperCase &= force;
633 cs.hasStarredVersion &= full;
634 string const command = citationStyleToString(cs);
636 params_.setCmdName(command);
637 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
638 params_["before"] = qstring_to_ucs4(before);
639 params_["after"] = qstring_to_ucs4(after);
640 if (cs.hasQualifiedList) {
641 params_["pretextlist"] = getStringFromVector(getPreTexts(), from_ascii("\t"));
642 params_["posttextlist"] = getStringFromVector(getPostTexts(), from_ascii("\t"));
644 params_["literal"] = literalCB->isChecked() ? from_ascii("true") : from_ascii("false");
649 void GuiCitation::clearSelection()
652 setSelectedKeys(cited_keys_);
656 void GuiCitation::setSelectedKeys(QStringList const & sl)
658 selected_model_.clear();
659 selected_model_.setColumnCount(3);
661 headers << qt_("Text before")
663 << qt_("Text after");
664 selected_model_.setHorizontalHeaderLabels(headers);
665 selectedLV->setColumnHidden(0, true);
666 selectedLV->setColumnHidden(2, true);
667 selectedLV->verticalHeader()->setVisible(false);
668 selectedLV->horizontalHeader()->setVisible(false);
669 QStringList::const_iterator it = sl.begin();
670 QStringList::const_iterator end = sl.end();
671 for (int i = 0; it != end; ++it, ++i) {
672 QStandardItem * si = new QStandardItem();
676 si->setEditable(false);
677 selected_model_.setItem(i, 1, si);
682 QStringList GuiCitation::selectedKeys()
685 for (int i = 0; i != selected_model_.rowCount(); ++i) {
686 QStandardItem const * item = selected_model_.item(i, 1);
688 res.append(item->text());
694 void GuiCitation::setPreTexts(vector<docstring> const & m)
696 // account for multiple use of the same keys
697 QList<QModelIndex> handled;
698 for (docstring const & s: m) {
699 QStandardItem * si = new QStandardItem();
701 docstring pre = split(s, key, ' ');
702 si->setData(toqstr(pre));
703 si->setText(toqstr(pre));
704 QModelIndexList qmil =
705 selected_model_.match(selected_model_.index(0, 1),
706 Qt::DisplayRole, toqstr(key), -1,
707 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
708 for (auto const & idx : qmil) {
709 if (!handled.contains(idx)) {
710 selected_model_.setItem(idx.row(), 0, si);
719 vector<docstring> GuiCitation::getPreTexts()
721 vector<docstring> res;
722 for (int i = 0; i != selected_model_.rowCount(); ++i) {
723 QStandardItem const * key = selected_model_.item(i, 1);
724 QStandardItem const * pre = selected_model_.item(i, 0);
725 if (key && pre && !key->text().isEmpty())
726 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(pre->text()));
732 void GuiCitation::setPostTexts(vector<docstring> const & m)
734 // account for multiple use of the same keys
735 QList<QModelIndex> handled;
736 for (docstring const & s: m) {
737 QStandardItem * si = new QStandardItem();
739 docstring post = split(s, key, ' ');
740 si->setData(toqstr(post));
741 si->setText(toqstr(post));
742 QModelIndexList qmil =
743 selected_model_.match(selected_model_.index(0, 1),
744 Qt::DisplayRole, toqstr(key), -1,
745 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
746 for (auto const & idx : qmil) {
747 if (!handled.contains(idx)) {
748 selected_model_.setItem(idx.row(), 2, si);
757 vector<docstring> GuiCitation::getPostTexts()
759 vector<docstring> res;
760 for (int i = 0; i != selected_model_.rowCount(); ++i) {
761 QStandardItem const * key = selected_model_.item(i, 1);
762 QStandardItem const * post = selected_model_.item(i, 2);
763 if (key && post && !key->text().isEmpty())
764 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(post->text()));
770 void GuiCitation::init()
772 // Make the list of all available bibliography keys
773 BiblioInfo const & bi = bibInfo();
774 all_keys_ = to_qstring_list(bi.getKeys());
776 available_model_.setStringList(all_keys_);
778 // Ditto for the keys cited in this inset
779 QString str = toqstr(params_["key"]);
783 cited_keys_ = str.split(",");
784 setSelectedKeys(cited_keys_);
786 // Initialize the drop downs
790 // Initialize the citation formatting
791 string const & cmd = params_.getCmdName();
792 CitationStyle const cs =
793 citationStyleFromString(cmd, documentBuffer().params());
795 forceuppercaseCB->setChecked(cs.forceUpperCase);
796 starredCB->setChecked(cs.hasStarredVersion &&
797 documentBuffer().params().fullAuthorList());
798 textBeforeED->setText(toqstr(params_["before"]));
799 textAfterED->setText(toqstr(params_["after"]));
801 // if this is a new citation, we set the literal checkbox
802 // to its last set value.
803 if (cited_keys_.isEmpty())
804 literalCB->setChecked(InsetCitation::last_literal);
806 literalCB->setChecked(params_["literal"] == "true");
808 setPreTexts(getVectorFromString(params_["pretextlist"], from_ascii("\t")));
809 setPostTexts(getVectorFromString(params_["posttextlist"], from_ascii("\t")));
811 // Update the interface
814 if (selected_model_.rowCount()) {
815 selectedLV->blockSignals(true);
816 selectedLV->setFocus();
817 selectedLV->selectRow(0);
818 selectedLV->blockSignals(false);
820 // Find the citation style
821 vector<string> const & cmds = citeCmds_;
822 vector<string>::const_iterator cit =
823 std::find(cmds.begin(), cmds.end(), cs.name);
825 if (cit != cmds.end())
826 i = int(cit - cmds.begin());
828 // Set the style combo appropriately
829 citationStyleCO->blockSignals(true);
830 citationStyleCO->setCurrentIndex(i);
831 citationStyleCO->blockSignals(false);
832 updateFormatting(citeStyles_[size_type(i)]);
834 availableLV->setFocus();
836 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
837 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
841 void GuiCitation::findKey(BiblioInfo const & bi,
842 QString const & str, bool only_keys,
843 docstring field, docstring entry_type,
844 bool case_sensitive, bool reg_exp, bool reset)
847 // This should be moved to a class member.
848 // Used for optimisation: store last searched string.
849 static QString last_searched_string;
850 // Used to disable the above optimisation.
851 static bool last_case_sensitive;
852 static bool last_reg_exp;
853 // Reset last_searched_string in case of changed option.
854 if (last_case_sensitive != case_sensitive
855 || last_reg_exp != reg_exp) {
856 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
857 last_searched_string.clear();
859 // save option for next search.
860 last_case_sensitive = case_sensitive;
861 last_reg_exp = reg_exp;
863 Qt::CaseSensitivity qtcase = case_sensitive ?
864 Qt::CaseSensitive: Qt::CaseInsensitive;
866 // If new string (str) contains the last searched one...
868 !last_searched_string.isEmpty() &&
870 str.contains(last_searched_string, qtcase))
871 // ... then only search within already found list.
872 keys = available_model_.stringList();
874 // ... else search all keys.
876 // save searched string for next search.
877 last_searched_string = str;
881 // First, filter by entry_type, which will be faster than
882 // what follows, so we may get to do that on less.
883 vector<docstring> keyVector = to_docstring_vector(keys);
884 filterByEntryType(bi, keyVector, entry_type);
887 result = to_qstring_list(keyVector);
889 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
890 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
892 available_model_.setStringList(result);
896 BiblioInfo::CiteStringMap GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
898 vector<docstring> const keys = to_docstring_vector(cited_keys_);
899 vector<CitationStyle> styles = citeStyles_;
900 int ind = citationStyleCO->currentIndex();
903 CitationStyle cs = styles[size_type(ind)];
904 vector<docstring> pretexts = getPreTexts();
905 vector<docstring> posttexts = getPostTexts();
906 bool const qualified = cs.hasQualifiedList
907 && (selectedLV->model()->rowCount() > 1
909 || !posttexts.empty());
910 vector<pair<docstring, docstring>> pres;
911 for (docstring const & s: pretexts) {
913 docstring val = split(s, key, ' ');
914 pres.push_back(make_pair(key, val));
916 vector<pair<docstring, docstring>> posts;
917 for (docstring const & s: posttexts) {
919 docstring val = split(s, key, ' ');
920 posts.push_back(make_pair(key, val));
923 ci.textBefore = qstring_to_ucs4(textBeforeED->text());
924 ci.textAfter = qstring_to_ucs4(textAfterED->text());
925 ci.forceUpperCase = forceuppercaseCB->isChecked();
926 ci.Starred = starredCB->isChecked();
927 ci.context = CiteItem::Dialog;
928 ci.max_size = max_size;
929 ci.isQualified = qualified;
931 ci.posttexts = posts;
932 BiblioInfo::CiteStringMap ret = bi.getCiteStrings(keys, styles, documentBuffer(), ci);
937 void GuiCitation::setCitedKeys()
939 cited_keys_ = selectedKeys();
944 bool GuiCitation::initialiseParams(string const & sdata)
946 InsetCommand::string2params(sdata, params_);
947 citeCmds_ = documentBuffer().params().citeCommands();
948 citeStyles_ = documentBuffer().params().citeStyles();
954 void GuiCitation::clearParams()
960 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
961 vector<docstring> & keyVector, docstring const & entry_type)
963 if (entry_type.empty())
966 vector<docstring>::iterator it = keyVector.begin();
967 vector<docstring>::iterator end = keyVector.end();
969 vector<docstring> result;
970 for (; it != end; ++it) {
971 docstring const key = *it;
972 BiblioInfo::const_iterator cit = bi.find(key);
975 if (cit->second.entryType() == entry_type)
976 result.push_back(key);
982 // Escape special chars.
983 // All characters are literals except: '.|*?+(){}[]^$\'
984 // These characters are literals when preceded by a "\", which is done here
985 // @todo: This function should be moved to support, and then the test in tests
986 // should be moved there as well.
987 static docstring escape_special_chars(docstring const & expr)
989 // Search for all chars '.|*?+(){}[^$]\'
990 // Note that '[', ']', and '\' must be escaped.
991 static const regex reg("[.|*?+(){}^$\\[\\]\\\\]");
993 // $& is an ECMAScript format expression that expands to all
994 // of the current match
995 // To prefix a matched expression with a single literal backslash, we
996 // need to escape it for the C++ compiler and use:
998 return from_utf8(regex_replace(to_utf8(expr), reg, string("\\$&")));
1002 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
1003 vector<docstring> const & keys_to_search, bool only_keys,
1004 docstring const & search_expression, docstring const & field,
1005 bool case_sensitive, bool re)
1007 vector<docstring> foundKeys;
1009 docstring expr = trim(search_expression);
1014 // We must escape special chars in the search_expr so that
1015 // it is treated as a simple string by regex.
1016 expr = escape_special_chars(expr);
1020 reg_exp.assign(to_utf8(expr), case_sensitive ?
1021 regex_constants::ECMAScript : regex_constants::icase);
1022 } catch (regex_error const & e) {
1023 // regex throws an exception if the regular expression is not
1025 LYXERR(Debug::GUI, e.what());
1026 return vector<docstring>();
1029 vector<docstring>::const_iterator it = keys_to_search.begin();
1030 vector<docstring>::const_iterator end = keys_to_search.end();
1031 for (; it != end; ++it ) {
1032 BiblioInfo::const_iterator info = bi.find(*it);
1033 if (info == bi.end())
1036 BibTeXInfo const & kvm = info->second;
1039 sdata = to_utf8(*it);
1040 else if (field.empty())
1041 sdata = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
1043 sdata = to_utf8(kvm[field]);
1049 if (regex_search(sdata, reg_exp))
1050 foundKeys.push_back(*it);
1052 catch (regex_error const & e) {
1053 LYXERR(Debug::GUI, e.what());
1054 return vector<docstring>();
1061 void GuiCitation::dispatchParams()
1063 std::string const lfun = InsetCommand::params2string(params_);
1064 dispatch(FuncRequest(getLfun(), lfun));
1068 BiblioInfo const & GuiCitation::bibInfo() const
1070 Buffer const & buf = documentBuffer();
1071 buf.reloadBibInfoCache();
1072 return buf.masterBibInfo();
1076 void GuiCitation::saveSession(QSettings & settings) const
1078 Dialog::saveSession(settings);
1080 sessionKey() + "/regex", regexp_->isChecked());
1082 sessionKey() + "/casesensitive", casesense_->isChecked());
1084 sessionKey() + "/autofind", instant_->isChecked());
1086 sessionKey() + "/citestyle", style_);
1088 sessionKey() + "/literal", InsetCitation::last_literal);
1092 void GuiCitation::restoreSession()
1094 Dialog::restoreSession();
1096 regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
1097 casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
1098 instant_->setChecked(settings.value(sessionKey() + "/autofind", true).toBool());
1099 style_ = settings.value(sessionKey() + "/citestyle").toString();
1100 InsetCitation::last_literal =
1101 settings.value(sessionKey() + "/literal", false).toBool();
1106 } // namespace frontend
1109 #include "moc_GuiCitation.cpp"