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_->setButtonPixmap(FancyLineEdit::Right, getPixmap("images/", "editclear", "svgz,png"));
102 filter_->setButtonVisible(FancyLineEdit::Right, true);
103 filter_->setButtonToolTip(FancyLineEdit::Right, qt_("Clear text"));
104 filter_->setAutoHideButton(FancyLineEdit::Right, true);
105 filter_->setPlaceholderText(qt_("All avail. citations"));
107 filterBarL->addWidget(filter_, 0);
108 findKeysLA->setBuddy(filter_);
110 // Add search options as button menu
111 regexp_ = new QAction(qt_("Regular e&xpression"), this);
112 regexp_->setCheckable(true);
113 casesense_ = new QAction(qt_("Case se&nsitive"), this);
114 casesense_->setCheckable(true);
115 instant_ = new QAction(qt_("Search as you &type"), this);
116 instant_->setCheckable(true);
117 instant_->setChecked(true);
119 QMenu * searchOpts = new QMenu(this);
120 searchOpts->addAction(regexp_);
121 searchOpts->addAction(casesense_);
122 searchOpts->addAction(instant_);
123 searchOptionsPB->setMenu(searchOpts);
125 connect(citationStyleCO, SIGNAL(activated(int)),
126 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
127 connect(starredCB, SIGNAL(clicked()),
128 this, SLOT(updateStyles()));
129 connect(literalCB, SIGNAL(clicked()),
130 this, SLOT(changed()));
131 connect(forceuppercaseCB, SIGNAL(clicked()),
132 this, SLOT(updateStyles()));
133 connect(textBeforeED, SIGNAL(textChanged(QString)),
134 this, SLOT(updateStyles()));
135 connect(textAfterED, SIGNAL(textChanged(QString)),
136 this, SLOT(updateStyles()));
137 connect(textBeforeED, SIGNAL(returnPressed()),
138 this, SLOT(on_buttonBox_accepted()));
139 connect(textAfterED, SIGNAL(returnPressed()),
140 this, SLOT(on_buttonBox_accepted()));
142 selectionManager = new GuiSelectionManager(this, availableLV, selectedLV,
143 addPB, deletePB, upPB, downPB, &available_model_, &selected_model_, 1);
144 connect(selectionManager, SIGNAL(selectionChanged()),
145 this, SLOT(setCitedKeys()));
146 connect(selectionManager, SIGNAL(updateHook()),
147 this, SLOT(updateControls()));
148 connect(selectionManager, SIGNAL(okHook()),
149 this, SLOT(on_buttonBox_accepted()));
151 connect(filter_, SIGNAL(rightButtonClicked()),
152 this, SLOT(resetFilter()));
153 connect(filter_, SIGNAL(textEdited(QString)),
154 this, SLOT(filterChanged(QString)));
155 connect(filter_, SIGNAL(returnPressed()),
156 this, SLOT(filterPressed()));
157 #if (QT_VERSION < 0x050000)
158 connect(filter_, SIGNAL(downPressed()),
159 availableLV, SLOT(setFocus()));
161 connect(filter_, &FancyLineEdit::downPressed,
162 availableLV, [this](){ focusAndHighlight(availableLV); });
164 connect(regexp_, SIGNAL(triggered()),
165 this, SLOT(regexChanged()));
166 connect(casesense_, SIGNAL(triggered()),
167 this, SLOT(caseChanged()));
168 connect(instant_, SIGNAL(triggered(bool)),
169 this, SLOT(instantChanged(bool)));
171 #if (QT_VERSION < 0x050000)
172 selectedLV->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
174 selectedLV->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
177 selectedLV->setToolTip(qt_("Ordered list of all cited references.\n"
178 "You can reorder, add and remove references with the buttons on the left."));
179 setFocusProxy(filter_);
183 void GuiCitation::closeEvent(QCloseEvent * e)
186 DialogView::closeEvent(e);
190 void GuiCitation::applyView()
192 int const choice = max(0, citationStyleCO->currentIndex());
193 style_ = citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
194 bool const full = starredCB->isChecked();
195 bool const force = forceuppercaseCB->isChecked();
197 QString const before = textBeforeED->text();
198 QString const after = textAfterED->text();
200 applyParams(choice, full, force, before, after);
202 // If we have just created a citation inset, then we want to attach the
203 // dialog to it. This (i) allows further modification of that inset and
204 // (ii) prevents an additional click on Apply or OK from unexpectedly
205 // creating another inset. (See #3964.)
206 GuiView & view = const_cast<GuiView &>(lyxview());
207 BufferView * bv = view.currentBufferView();
208 // should have one, but just to be safe...
210 // are we attached to an inset already?
211 Inset * ins = bv->editedInset("citation");
213 // no, so we just inserted one, and now we are behind it.
214 Cursor const & cur = bv->cursor();
215 ins = cur.prevInset();
217 bv->editInset("citation", ins);
223 void GuiCitation::showEvent(QShowEvent * e)
225 if (!filter_->text().isEmpty())
227 availableLV->setFocus();
228 DialogView::showEvent(e);
232 void GuiCitation::on_buttonBox_accepted()
240 void GuiCitation::on_buttonBox_rejected()
247 void GuiCitation::on_buttonBox_clicked(QAbstractButton * button)
249 switch (buttonBox->standardButton(button)) {
250 case QDialogButtonBox::Apply:
253 case QDialogButtonBox::Reset:
264 void GuiCitation::on_literalCB_clicked()
266 InsetCitation::last_literal = literalCB->isChecked();
271 void GuiCitation::updateControls()
273 BiblioInfo const & bi = bibInfo();
278 // The main point of separating this out is that the fill*() methods
279 // called in update() do not need to be called for INTERNAL updates,
280 // such as when addPB is pressed, as the list of fields, entries, etc,
281 // will not have changed.
282 void GuiCitation::updateControls(BiblioInfo const & bi)
284 QModelIndex idx = selectionManager->getSelectedIndex(1);
286 int i = citationStyleCO->currentIndex();
287 if (i == -1 || i > int(citeStyles_.size()))
289 updateFormatting(citeStyles_[size_type(i)]);
290 selectionManager->update();
294 void GuiCitation::updateFormatting(CitationStyle const & currentStyle)
296 BufferParams const bp = documentBuffer().params();
297 bool const force = currentStyle.forceUpperCase;
298 bool const starred = currentStyle.hasStarredVersion;
299 bool const full = starred && bp.fullAuthorList();
300 bool const textbefore = currentStyle.textBefore;
301 bool const textafter = currentStyle.textAfter;
303 int const rows = selectedLV->model()->rowCount();
305 bool const qualified = currentStyle.hasQualifiedList && rows > 0;
307 selectedLV->horizontalHeader()->setVisible(qualified);
308 selectedLV->setColumnHidden(0, !qualified);
309 selectedLV->setColumnHidden(2, !qualified);
310 bool const haveSelection = rows > 0;
312 textBeforeLA->setText(qt_("General text befo&re:"));
313 textAfterLA->setText(qt_("General &text after:"));
314 textBeforeED->setToolTip(qt_("Text that precedes the whole reference list. "
315 "For text that precedes individual items, "
316 "double-click on the respective entry above."));
317 textAfterLA->setToolTip(qt_("General &text after:"));
318 textAfterED->setToolTip(qt_("Text that follows the whole reference list. "
319 "For text that follows individual items, "
320 "double-click on the respective entry above."));
322 textBeforeLA->setText(qt_("Text befo&re:"));
323 if (textbefore && haveSelection)
324 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\")"));
326 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\"), "
327 "if the current citation style supports this."));
328 textAfterLA->setText(qt_("&Text after:"));
329 if (textafter && haveSelection)
330 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages)"));
332 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages), "
333 "if the current citation style supports this."));
336 forceuppercaseCB->setEnabled(force && haveSelection);
337 if (force && haveSelection)
338 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\")."));
340 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\"), "
341 "if the current citation style supports this."));
342 starredCB->setEnabled(full && haveSelection);
343 textBeforeED->setEnabled(textbefore && haveSelection);
344 textBeforeLA->setEnabled(textbefore && haveSelection);
345 textAfterED->setEnabled(textafter && haveSelection);
346 textAfterLA->setEnabled(textafter && haveSelection);
347 literalCB->setEnabled(textbefore || textafter);
348 citationStyleCO->setEnabled(haveSelection);
349 citationStyleLA->setEnabled(haveSelection);
351 // Check if we have a custom string/tooltip for the starred version
352 if (starred && !currentStyle.stardesc.empty()) {
354 bp.documentClass().getCiteMacro(bp.citeEngineType(), currentStyle.stardesc);
357 guistring = translateIfPossible(from_utf8(val));
358 starredCB->setText(toqstr(guistring));
359 starredCB->setEnabled(haveSelection);
361 if (!currentStyle.startooltip.empty()) {
362 val = bp.documentClass().getCiteMacro(bp.citeEngineType(),
363 currentStyle.startooltip);
365 guistring = translateIfPossible(from_utf8(val));
367 // Tooltip might also be empty
368 starredCB->setToolTip(toqstr(guistring));
370 // This is the default meaning of the starred commands
371 starredCB->setText(qt_("All aut&hors"));
372 if (full && haveSelection)
373 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\")"));
375 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\"), "
376 "if the current citation style supports this."));
378 if (availableLV->selectionModel()->selectedIndexes().isEmpty())
379 availableLV->setToolTip(qt_("All references available for citing."));
381 availableLV->setToolTip(qt_("All references available for citing.\n"
382 "To add the selected one, hit Add, press Enter or double-click.\n"
383 "Hit Ctrl-Enter to add and close the dialog."));
384 // With qualified citation lists, it makes sense to add the same key multiple times
385 selectionManager->allowMultiSelection(currentStyle.hasQualifiedList);
389 // Update the styles for the style combo, citationStyleCO, and mark the
390 // settings as changed. Called upon changing the cited keys (including
391 // merely reordering the keys) or editing the text before/after fields.
392 void GuiCitation::updateStyles()
394 BiblioInfo const & bi = bibInfo();
400 // Update the styles for the style combo, citationStyleCO.
401 void GuiCitation::updateStyles(BiblioInfo const & bi)
403 QStringList selected_keys = selectedKeys();
404 int curr = selectedLV->model()->rowCount() - 1;
406 if (curr < 0 || selected_keys.empty()) {
408 citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
409 citationStyleCO->clear();
410 citationStyleCO->setEnabled(false);
411 citationStyleLA->setEnabled(false);
415 static const size_t max_length = 80;
416 BiblioInfo::CiteStringMap sty = citationStyles(bi, max_length);
420 citationStyleCO->setEnabled(false);
421 citationStyleLA->setEnabled(false);
422 citationStyleCO->clear();
426 citationStyleCO->blockSignals(true);
428 // save old style selection
429 QString const curdata =
430 citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
431 QString const olddata = (curdata.isEmpty()) ?
432 (last_chosen_style_.isEmpty() ? style_ : last_chosen_style_): curdata;
434 last_chosen_style_.clear();
435 citationStyleCO->clear();
436 BiblioInfo::CiteStringMap::const_iterator cit = sty.begin();
437 BiblioInfo::CiteStringMap::const_iterator end = sty.end();
438 for (int ii = 1; cit != end; ++cit, ++ii)
439 citationStyleCO->addItem(toqstr(cit->second), toqstr(cit->first));
440 citationStyleCO->setEnabled(true);
441 citationStyleLA->setEnabled(true);
442 // restore old style selection
443 int const i = citationStyleCO->findData(olddata);
445 citationStyleCO->setCurrentIndex(i);
447 citationStyleCO->blockSignals(false);
451 void GuiCitation::fillFields(BiblioInfo const & bi)
453 fieldsCO->blockSignals(true);
454 int const oldIndex = fieldsCO->currentIndex();
456 QStringList const fields = to_qstring_list(bi.getFields());
457 fieldsCO->insertItem(0, qt_("All fields"));
458 fieldsCO->insertItem(1, qt_("Keys"));
459 fieldsCO->insertItems(2, fields);
460 if (oldIndex != -1 && oldIndex < fieldsCO->count())
461 fieldsCO->setCurrentIndex(oldIndex);
462 fieldsCO->blockSignals(false);
466 void GuiCitation::fillEntries(BiblioInfo const & bi)
468 entriesCO->blockSignals(true);
469 int const oldIndex = entriesCO->currentIndex();
471 QStringList const entries = to_qstring_list(bi.getEntries());
472 entriesCO->insertItem(0, qt_("All entry types"));
473 entriesCO->insertItems(1, entries);
474 if (oldIndex != -1 && oldIndex < entriesCO->count())
475 entriesCO->setCurrentIndex(oldIndex);
476 entriesCO->blockSignals(false);
480 bool GuiCitation::isSelected(QModelIndex const & idx)
482 QString const str = idx.data().toString();
483 return selectedKeys().contains(str);
487 void GuiCitation::setButtons()
489 int const srows = selectedLV->model()->rowCount();
490 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(srows > 0);
491 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(srows > 0);
495 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
497 if (!idx.isValid() || bi.empty()) {
498 infoML->document()->clear();
499 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
503 infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
506 QString const keytxt = toqstr(
507 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), ci));
508 infoML->document()->setHtml(keytxt);
512 void GuiCitation::findText(QString const & text, bool reset)
514 //"All Fields" and "Keys" are the first two
515 int index = fieldsCO->currentIndex() - 2;
516 BiblioInfo const & bi = bibInfo();
517 vector<docstring> const & fields = bi.getFields();
520 if (index <= -1 || index >= int(fields.size()))
521 //either "All Fields" or "Keys" or an invalid value
522 field = from_ascii("");
524 field = fields[size_type(index)];
527 bool const onlyKeys = index == -1;
529 //"All Entry Types" is first.
530 index = entriesCO->currentIndex() - 1;
531 vector<docstring> const & entries = bi.getEntries();
532 docstring entry_type;
533 if (index < 0 || index >= int(entries.size()))
534 entry_type = from_ascii("");
536 entry_type = entries[size_type(index)];
538 bool const case_sentitive = casesense_->isChecked();
539 bool const reg_exp = regexp_->isChecked();
541 findKey(bi, text, onlyKeys, field, entry_type,
542 case_sentitive, reg_exp, reset);
544 //It'd be nice to save and restore the current selection in
545 //availableLV. Currently, we get an automatic reset, since the
552 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
554 findText(filter_->text(), true);
558 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
560 findText(filter_->text(), true);
564 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
566 if (index >= 0 && index < citationStyleCO->count()) {
567 vector<CitationStyle> const & styles = citeStyles_;
568 updateFormatting(styles[size_type(index)]);
574 void GuiCitation::filterChanged(const QString & text)
576 if (!text.isEmpty()) {
577 if (instant_->isChecked())
578 findText(filter_->text());
581 findText(filter_->text());
586 void GuiCitation::filterPressed()
588 findText(filter_->text(), true);
592 void GuiCitation::resetFilter()
594 filter_->setText(QString());
595 findText(filter_->text(), true);
599 void GuiCitation::caseChanged()
601 findText(filter_->text());
605 void GuiCitation::regexChanged()
607 findText(filter_->text());
611 void GuiCitation::updateFilterHint()
613 QString hint = instant_->isChecked() ?
614 qt_("Enter string to filter the list of available citations") :
615 qt_("Enter string to filter the list of available citations and press <Enter>");
616 hint += qt_("\nThe down arrow key will get you into the list of filtered citations.");
617 filter_->setToolTip(hint);
621 void GuiCitation::instantChanged(bool checked)
624 findText(filter_->text(), true);
630 void GuiCitation::changed()
636 void GuiCitation::applyParams(int const choice, bool full, bool force,
637 QString before, QString after)
639 if (cited_keys_.isEmpty())
642 vector<CitationStyle> const & styles = citeStyles_;
644 CitationStyle cs = styles[size_type(choice)];
651 cs.forceUpperCase &= force;
652 cs.hasStarredVersion &= full;
653 string const command = citationStyleToString(cs);
655 params_.setCmdName(command);
656 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
657 params_["before"] = qstring_to_ucs4(before);
658 params_["after"] = qstring_to_ucs4(after);
659 if (cs.hasQualifiedList) {
660 params_["pretextlist"] = getStringFromVector(getPreTexts(), from_ascii("\t"));
661 params_["posttextlist"] = getStringFromVector(getPostTexts(), from_ascii("\t"));
663 params_["literal"] = literalCB->isChecked() ? from_ascii("true") : from_ascii("false");
668 void GuiCitation::clearSelection()
671 setSelectedKeys(cited_keys_);
675 void GuiCitation::setSelectedKeys(QStringList const & sl)
677 selected_model_.clear();
678 selected_model_.setColumnCount(3);
680 headers << qt_("Text before")
682 << qt_("Text after");
683 selected_model_.setHorizontalHeaderLabels(headers);
684 selectedLV->setColumnHidden(0, true);
685 selectedLV->setColumnHidden(2, true);
686 selectedLV->verticalHeader()->setVisible(false);
687 selectedLV->horizontalHeader()->setVisible(false);
688 QStringList::const_iterator it = sl.begin();
689 QStringList::const_iterator end = sl.end();
690 for (int i = 0; it != end; ++it, ++i) {
691 QStandardItem * si = new QStandardItem();
695 si->setEditable(false);
696 selected_model_.setItem(i, 1, si);
701 QStringList GuiCitation::selectedKeys()
704 for (int i = 0; i != selected_model_.rowCount(); ++i) {
705 QStandardItem const * item = selected_model_.item(i, 1);
707 res.append(item->text());
713 void GuiCitation::setPreTexts(vector<docstring> const & m)
715 // account for multiple use of the same keys
716 QList<QModelIndex> handled;
717 for (docstring const & s: m) {
718 QStandardItem * si = new QStandardItem();
720 docstring pre = split(s, key, ' ');
721 si->setData(toqstr(pre));
722 si->setText(toqstr(pre));
723 QModelIndexList qmil =
724 selected_model_.match(selected_model_.index(0, 1),
725 Qt::DisplayRole, toqstr(key), -1,
726 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
727 for (auto const & idx : qmil) {
728 if (!handled.contains(idx)) {
729 selected_model_.setItem(idx.row(), 0, si);
738 vector<docstring> GuiCitation::getPreTexts()
740 vector<docstring> res;
741 for (int i = 0; i != selected_model_.rowCount(); ++i) {
742 QStandardItem const * key = selected_model_.item(i, 1);
743 QStandardItem const * pre = selected_model_.item(i, 0);
744 if (key && pre && !key->text().isEmpty())
745 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(pre->text()));
751 void GuiCitation::setPostTexts(vector<docstring> const & m)
753 // account for multiple use of the same keys
754 QList<QModelIndex> handled;
755 for (docstring const & s: m) {
756 QStandardItem * si = new QStandardItem();
758 docstring post = split(s, key, ' ');
759 si->setData(toqstr(post));
760 si->setText(toqstr(post));
761 QModelIndexList qmil =
762 selected_model_.match(selected_model_.index(0, 1),
763 Qt::DisplayRole, toqstr(key), -1,
764 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
765 for (auto const & idx : qmil) {
766 if (!handled.contains(idx)) {
767 selected_model_.setItem(idx.row(), 2, si);
776 vector<docstring> GuiCitation::getPostTexts()
778 vector<docstring> res;
779 for (int i = 0; i != selected_model_.rowCount(); ++i) {
780 QStandardItem const * key = selected_model_.item(i, 1);
781 QStandardItem const * post = selected_model_.item(i, 2);
782 if (key && post && !key->text().isEmpty())
783 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(post->text()));
789 void GuiCitation::init()
791 // Make the list of all available bibliography keys
792 BiblioInfo const & bi = bibInfo();
793 all_keys_ = to_qstring_list(bi.getKeys());
795 available_model_.setStringList(all_keys_);
797 // Ditto for the keys cited in this inset
798 QString str = toqstr(params_["key"]);
802 cited_keys_ = str.split(",");
803 setSelectedKeys(cited_keys_);
805 // Initialize the drop downs
809 // Initialize the citation formatting
810 string const & cmd = params_.getCmdName();
811 CitationStyle const cs =
812 citationStyleFromString(cmd, documentBuffer().params());
814 forceuppercaseCB->setChecked(cs.forceUpperCase);
815 starredCB->setChecked(cs.hasStarredVersion &&
816 documentBuffer().params().fullAuthorList());
817 textBeforeED->setText(toqstr(params_["before"]));
818 textAfterED->setText(toqstr(params_["after"]));
820 // if this is a new citation, we set the literal checkbox
821 // to its last set value.
822 if (cited_keys_.isEmpty())
823 literalCB->setChecked(InsetCitation::last_literal);
825 literalCB->setChecked(params_["literal"] == "true");
827 setPreTexts(getVectorFromString(params_["pretextlist"], from_ascii("\t")));
828 setPostTexts(getVectorFromString(params_["posttextlist"], from_ascii("\t")));
830 // Update the interface
833 if (selected_model_.rowCount()) {
834 selectedLV->blockSignals(true);
835 selectedLV->setFocus();
836 selectedLV->selectRow(0);
837 selectedLV->blockSignals(false);
839 // Find the citation style
840 vector<string> const & cmds = citeCmds_;
841 vector<string>::const_iterator cit =
842 std::find(cmds.begin(), cmds.end(), cs.name);
844 if (cit != cmds.end())
845 i = int(cit - cmds.begin());
847 // Set the style combo appropriately
848 citationStyleCO->blockSignals(true);
849 citationStyleCO->setCurrentIndex(i);
850 citationStyleCO->blockSignals(false);
851 updateFormatting(citeStyles_[size_type(i)]);
853 availableLV->setFocus();
855 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
856 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
860 void GuiCitation::findKey(BiblioInfo const & bi,
861 QString const & str, bool only_keys,
862 docstring field, docstring entry_type,
863 bool case_sensitive, bool reg_exp, bool reset)
866 // This should be moved to a class member.
867 // Used for optimisation: store last searched string.
868 static QString last_searched_string;
869 // Used to disable the above optimisation.
870 static bool last_case_sensitive;
871 static bool last_reg_exp;
872 // Reset last_searched_string in case of changed option.
873 if (last_case_sensitive != case_sensitive
874 || last_reg_exp != reg_exp) {
875 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
876 last_searched_string.clear();
878 // save option for next search.
879 last_case_sensitive = case_sensitive;
880 last_reg_exp = reg_exp;
882 Qt::CaseSensitivity qtcase = case_sensitive ?
883 Qt::CaseSensitive: Qt::CaseInsensitive;
885 // If new string (str) contains the last searched one...
887 !last_searched_string.isEmpty() &&
889 str.contains(last_searched_string, qtcase))
890 // ... then only search within already found list.
891 keys = available_model_.stringList();
893 // ... else search all keys.
895 // save searched string for next search.
896 last_searched_string = str;
900 // First, filter by entry_type, which will be faster than
901 // what follows, so we may get to do that on less.
902 vector<docstring> keyVector = to_docstring_vector(keys);
903 filterByEntryType(bi, keyVector, entry_type);
906 result = to_qstring_list(keyVector);
908 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
909 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
911 available_model_.setStringList(result);
915 BiblioInfo::CiteStringMap GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
917 vector<docstring> const keys = to_docstring_vector(cited_keys_);
918 vector<CitationStyle> styles = citeStyles_;
919 int ind = citationStyleCO->currentIndex();
922 CitationStyle cs = styles[size_type(ind)];
923 vector<docstring> pretexts = getPreTexts();
924 vector<docstring> posttexts = getPostTexts();
925 bool const qualified = cs.hasQualifiedList
926 && (selectedLV->model()->rowCount() > 1
928 || !posttexts.empty());
929 vector<pair<docstring, docstring>> pres;
930 for (docstring const & s: pretexts) {
932 docstring val = split(s, key, ' ');
933 pres.push_back(make_pair(key, val));
935 vector<pair<docstring, docstring>> posts;
936 for (docstring const & s: posttexts) {
938 docstring val = split(s, key, ' ');
939 posts.push_back(make_pair(key, val));
942 ci.textBefore = qstring_to_ucs4(textBeforeED->text());
943 ci.textAfter = qstring_to_ucs4(textAfterED->text());
944 ci.forceUpperCase = forceuppercaseCB->isChecked();
945 ci.Starred = starredCB->isChecked();
946 ci.context = CiteItem::Dialog;
947 ci.max_size = max_size;
948 ci.isQualified = qualified;
950 ci.posttexts = posts;
951 BiblioInfo::CiteStringMap ret = bi.getCiteStrings(keys, styles, documentBuffer(), ci);
956 void GuiCitation::setCitedKeys()
958 cited_keys_ = selectedKeys();
963 bool GuiCitation::initialiseParams(string const & sdata)
965 InsetCommand::string2params(sdata, params_);
966 citeCmds_ = documentBuffer().params().citeCommands();
967 citeStyles_ = documentBuffer().params().citeStyles();
973 void GuiCitation::clearParams()
979 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
980 vector<docstring> & keyVector, docstring const & entry_type)
982 if (entry_type.empty())
985 vector<docstring>::iterator it = keyVector.begin();
986 vector<docstring>::iterator end = keyVector.end();
988 vector<docstring> result;
989 for (; it != end; ++it) {
990 docstring const key = *it;
991 BiblioInfo::const_iterator cit = bi.find(key);
994 if (cit->second.entryType() == entry_type)
995 result.push_back(key);
1001 // Escape special chars.
1002 // All characters are literals except: '.|*?+(){}[]^$\'
1003 // These characters are literals when preceded by a "\", which is done here
1004 // @todo: This function should be moved to support, and then the test in tests
1005 // should be moved there as well.
1006 static docstring escape_special_chars(docstring const & expr)
1008 // Search for all chars '.|*?+(){}[^$]\'
1009 // Note that '[', ']', and '\' must be escaped.
1010 static const regex reg("[.|*?+(){}^$\\[\\]\\\\]");
1012 // $& is an ECMAScript format expression that expands to all
1013 // of the current match
1014 // To prefix a matched expression with a single literal backslash, we
1015 // need to escape it for the C++ compiler and use:
1017 return from_utf8(regex_replace(to_utf8(expr), reg, string("\\$&")));
1021 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
1022 vector<docstring> const & keys_to_search, bool only_keys,
1023 docstring const & search_expression, docstring const & field,
1024 bool case_sensitive, bool re)
1026 vector<docstring> foundKeys;
1028 docstring expr = trim(search_expression);
1033 // We must escape special chars in the search_expr so that
1034 // it is treated as a simple string by regex.
1035 expr = escape_special_chars(expr);
1039 reg_exp.assign(to_utf8(expr), case_sensitive ?
1040 regex_constants::ECMAScript : regex_constants::icase);
1041 } catch (regex_error const & e) {
1042 // regex throws an exception if the regular expression is not
1044 LYXERR(Debug::GUI, e.what());
1045 return vector<docstring>();
1048 vector<docstring>::const_iterator it = keys_to_search.begin();
1049 vector<docstring>::const_iterator end = keys_to_search.end();
1050 for (; it != end; ++it ) {
1051 BiblioInfo::const_iterator info = bi.find(*it);
1052 if (info == bi.end())
1055 BibTeXInfo const & kvm = info->second;
1058 sdata = to_utf8(*it);
1059 else if (field.empty())
1060 sdata = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
1062 sdata = to_utf8(kvm[field]);
1068 if (regex_search(sdata, reg_exp))
1069 foundKeys.push_back(*it);
1071 catch (regex_error const & e) {
1072 LYXERR(Debug::GUI, e.what());
1073 return vector<docstring>();
1080 void GuiCitation::dispatchParams()
1082 std::string const lfun = InsetCommand::params2string(params_);
1083 dispatch(FuncRequest(getLfun(), lfun));
1087 BiblioInfo const & GuiCitation::bibInfo() const
1089 Buffer const & buf = documentBuffer();
1090 buf.reloadBibInfoCache();
1091 return buf.masterBibInfo();
1095 void GuiCitation::saveSession(QSettings & settings) const
1097 Dialog::saveSession(settings);
1099 sessionKey() + "/regex", regexp_->isChecked());
1101 sessionKey() + "/casesensitive", casesense_->isChecked());
1103 sessionKey() + "/autofind", instant_->isChecked());
1105 sessionKey() + "/citestyle", style_);
1107 sessionKey() + "/literal", InsetCitation::last_literal);
1111 void GuiCitation::restoreSession()
1113 Dialog::restoreSession();
1115 regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
1116 casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
1117 instant_->setChecked(settings.value(sessionKey() + "/autofind", true).toBool());
1118 style_ = settings.value(sessionKey() + "/citestyle").toString();
1119 InsetCitation::last_literal =
1120 settings.value(sessionKey() + "/literal", false).toBool();
1125 } // namespace frontend
1128 #include "moc_GuiCitation.cpp"