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 Heck
12 * Full author contact details are available in file CREDITS.
17 #include "GuiCitation.h"
19 #include "GuiApplication.h"
20 #include "GuiSelectionManager.h"
21 #include "qt_helpers.h"
24 #include "BufferView.h"
25 #include "BufferParams.h"
26 #include "TextClass.h"
27 #include "FuncRequest.h"
29 #include "insets/InsetCitation.h"
30 #include "insets/InsetCommand.h"
32 #include "support/debug.h"
33 #include "support/docstring.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
37 #include <QCloseEvent>
41 #include <QStandardItemModel>
46 #include "support/regex.h"
53 using namespace lyx::support;
59 // I am guessing that it would not hurt to make these private members.
60 static vector<string> citeCmds_;
61 static vector<CitationStyle> citeStyles_;
64 template<typename String>
65 static QStringList to_qstring_list(vector<String> const & v)
69 for (size_t i = 0; i != v.size(); ++i) {
72 qlist.append(lyx::toqstr(v[i]));
78 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
80 vector<lyx::docstring> v;
81 for (int i = 0; i != qlist.size(); ++i) {
82 if (qlist[i].isEmpty())
84 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
90 GuiCitation::GuiCitation(GuiView & lv)
91 : DialogView(lv, "citation", qt_("Citation")),
92 style_(QString()), params_(insetCode("citation"))
97 filter_ = new FancyLineEdit(this);
98 filter_->setButtonPixmap(FancyLineEdit::Right, getPixmap("images/", "editclear", "svgz,png"));
99 filter_->setButtonVisible(FancyLineEdit::Right, true);
100 filter_->setButtonToolTip(FancyLineEdit::Right, qt_("Clear text"));
101 filter_->setAutoHideButton(FancyLineEdit::Right, 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(updateControls()));
145 connect(selectionManager, SIGNAL(okHook()),
146 this, SLOT(on_buttonBox_accepted()));
148 connect(filter_, SIGNAL(rightButtonClicked()),
149 this, SLOT(resetFilter()));
150 connect(filter_, SIGNAL(textEdited(QString)),
151 this, SLOT(filterChanged(QString)));
152 connect(filter_, SIGNAL(returnPressed()),
153 this, SLOT(filterPressed()));
154 #if (QT_VERSION < 0x050000)
155 connect(filter_, SIGNAL(downPressed()),
156 availableLV, SLOT(setFocus()));
158 connect(filter_, &FancyLineEdit::downPressed,
159 availableLV, [=](){ focusAndHighlight(availableLV); });
161 connect(regexp_, SIGNAL(triggered()),
162 this, SLOT(regexChanged()));
163 connect(casesense_, SIGNAL(triggered()),
164 this, SLOT(caseChanged()));
165 connect(instant_, SIGNAL(triggered(bool)),
166 this, SLOT(instantChanged(bool)));
168 #if (QT_VERSION < 0x050000)
169 selectedLV->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
171 selectedLV->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
174 selectedLV->setToolTip(qt_("Ordered list of all cited references.\n"
175 "You can reorder, add and remove references with the buttons on the left."));
176 setFocusProxy(filter_);
180 void GuiCitation::closeEvent(QCloseEvent * e)
183 DialogView::closeEvent(e);
187 void GuiCitation::applyView()
189 int const choice = max(0, citationStyleCO->currentIndex());
190 style_ = citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
191 bool const full = starredCB->isChecked();
192 bool const force = forceuppercaseCB->isChecked();
194 QString const before = textBeforeED->text();
195 QString const after = textAfterED->text();
197 applyParams(choice, full, force, before, after);
201 void GuiCitation::showEvent(QShowEvent * e)
203 if (!filter_->text().isEmpty())
205 availableLV->setFocus();
206 DialogView::showEvent(e);
210 void GuiCitation::on_buttonBox_accepted()
218 void GuiCitation::on_buttonBox_rejected()
225 void GuiCitation::on_buttonBox_clicked(QAbstractButton * button)
227 switch (buttonBox->standardButton(button)) {
228 case QDialogButtonBox::Apply:
231 case QDialogButtonBox::Reset:
242 void GuiCitation::on_literalCB_clicked()
244 InsetCitation::last_literal = literalCB->isChecked();
249 void GuiCitation::updateControls()
251 BiblioInfo const & bi = bibInfo();
256 // The main point of separating this out is that the fill*() methods
257 // called in update() do not need to be called for INTERNAL updates,
258 // such as when addPB is pressed, as the list of fields, entries, etc,
259 // will not have changed.
260 void GuiCitation::updateControls(BiblioInfo const & bi)
262 QModelIndex idx = selectionManager->getSelectedIndex(1);
264 int i = citationStyleCO->currentIndex();
265 if (i == -1 || i > int(citeStyles_.size()))
267 updateFormatting(citeStyles_[size_type(i)]);
268 selectionManager->update();
272 void GuiCitation::updateFormatting(CitationStyle const & currentStyle)
274 BufferParams const bp = documentBuffer().params();
275 bool const force = currentStyle.forceUpperCase;
276 bool const starred = currentStyle.hasStarredVersion;
277 bool const full = starred && bp.fullAuthorList();
278 bool const textbefore = currentStyle.textBefore;
279 bool const textafter = currentStyle.textAfter;
281 int const rows = selectedLV->model()->rowCount();
283 bool const qualified = currentStyle.hasQualifiedList && rows > 0;
285 selectedLV->horizontalHeader()->setVisible(qualified);
286 selectedLV->setColumnHidden(0, !qualified);
287 selectedLV->setColumnHidden(2, !qualified);
288 bool const haveSelection = rows > 0;
290 textBeforeLA->setText(qt_("General text befo&re:"));
291 textAfterLA->setText(qt_("General &text after:"));
292 textBeforeED->setToolTip(qt_("Text that precedes the whole reference list. "
293 "For text that precedes individual items, "
294 "double-click on the respective entry above."));
295 textAfterLA->setToolTip(qt_("General &text after:"));
296 textAfterED->setToolTip(qt_("Text that follows the whole reference list. "
297 "For text that follows individual items, "
298 "double-click on the respective entry above."));
300 textBeforeLA->setText(qt_("Text befo&re:"));
301 if (textbefore && haveSelection)
302 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\")"));
304 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\"), "
305 "if the current citation style supports this."));
306 textAfterLA->setText(qt_("&Text after:"));
307 if (textafter && haveSelection)
308 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages)"));
310 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages), "
311 "if the current citation style supports this."));
314 forceuppercaseCB->setEnabled(force && haveSelection);
315 if (force && haveSelection)
316 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\")."));
318 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\"), "
319 "if the current citation style supports this."));
320 starredCB->setEnabled(full && haveSelection);
321 textBeforeED->setEnabled(textbefore && haveSelection);
322 textBeforeLA->setEnabled(textbefore && haveSelection);
323 textAfterED->setEnabled(textafter && haveSelection);
324 textAfterLA->setEnabled(textafter && haveSelection);
325 literalCB->setEnabled(textbefore || textafter);
326 citationStyleCO->setEnabled(haveSelection);
327 citationStyleLA->setEnabled(haveSelection);
329 // Check if we have a custom string/tooltip for the starred version
330 if (starred && !currentStyle.stardesc.empty()) {
332 bp.documentClass().getCiteMacro(bp.citeEngineType(), currentStyle.stardesc);
335 guistring = translateIfPossible(from_utf8(val));
336 starredCB->setText(toqstr(guistring));
337 starredCB->setEnabled(haveSelection);
339 if (!currentStyle.startooltip.empty()) {
340 val = bp.documentClass().getCiteMacro(bp.citeEngineType(),
341 currentStyle.startooltip);
343 guistring = translateIfPossible(from_utf8(val));
345 // Tooltip might also be empty
346 starredCB->setToolTip(toqstr(guistring));
348 // This is the default meaning of the starred commands
349 starredCB->setText(qt_("All aut&hors"));
350 if (full && haveSelection)
351 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\")"));
353 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\"), "
354 "if the current citation style supports this."));
356 if (availableLV->selectionModel()->selectedIndexes().isEmpty())
357 availableLV->setToolTip(qt_("All references available for citing."));
359 availableLV->setToolTip(qt_("All references available for citing.\n"
360 "To add the selected one, hit Add, press Enter or double-click.\n"
361 "Hit Ctrl-Enter to add and close the dialog."));
362 // With qualified citation lists, it makes sense to add the same key multiple times
363 selectionManager->allowMultiSelection(currentStyle.hasQualifiedList);
367 // Update the styles for the style combo, citationStyleCO, and mark the
368 // settings as changed. Called upon changing the cited keys (including
369 // merely reordering the keys) or editing the text before/after fields.
370 void GuiCitation::updateStyles()
372 BiblioInfo const & bi = bibInfo();
378 // Update the styles for the style combo, citationStyleCO.
379 void GuiCitation::updateStyles(BiblioInfo const & bi)
381 QStringList selected_keys = selectedKeys();
382 int curr = selectedLV->model()->rowCount() - 1;
384 if (curr < 0 || selected_keys.empty()) {
386 citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
387 citationStyleCO->clear();
388 citationStyleCO->setEnabled(false);
389 citationStyleLA->setEnabled(false);
393 static const size_t max_length = 80;
394 BiblioInfo::CiteStringMap sty = citationStyles(bi, max_length);
398 citationStyleCO->setEnabled(false);
399 citationStyleLA->setEnabled(false);
400 citationStyleCO->clear();
404 citationStyleCO->blockSignals(true);
406 // save old style selection
407 QString const curdata =
408 citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
409 QString const olddata = (curdata.isEmpty()) ?
410 (last_chosen_style_.isEmpty() ? style_ : last_chosen_style_): curdata;
412 last_chosen_style_.clear();
413 citationStyleCO->clear();
414 BiblioInfo::CiteStringMap::const_iterator cit = sty.begin();
415 BiblioInfo::CiteStringMap::const_iterator end = sty.end();
416 for (int ii = 1; cit != end; ++cit, ++ii)
417 citationStyleCO->addItem(toqstr(cit->second), toqstr(cit->first));
418 citationStyleCO->setEnabled(true);
419 citationStyleLA->setEnabled(true);
420 // restore old style selection
421 int const i = citationStyleCO->findData(olddata);
423 citationStyleCO->setCurrentIndex(i);
425 citationStyleCO->blockSignals(false);
429 void GuiCitation::fillFields(BiblioInfo const & bi)
431 fieldsCO->blockSignals(true);
432 int const oldIndex = fieldsCO->currentIndex();
434 QStringList const fields = to_qstring_list(bi.getFields());
435 fieldsCO->insertItem(0, qt_("All fields"));
436 fieldsCO->insertItem(1, qt_("Keys"));
437 fieldsCO->insertItems(2, fields);
438 if (oldIndex != -1 && oldIndex < fieldsCO->count())
439 fieldsCO->setCurrentIndex(oldIndex);
440 fieldsCO->blockSignals(false);
444 void GuiCitation::fillEntries(BiblioInfo const & bi)
446 entriesCO->blockSignals(true);
447 int const oldIndex = entriesCO->currentIndex();
449 QStringList const entries = to_qstring_list(bi.getEntries());
450 entriesCO->insertItem(0, qt_("All entry types"));
451 entriesCO->insertItems(1, entries);
452 if (oldIndex != -1 && oldIndex < entriesCO->count())
453 entriesCO->setCurrentIndex(oldIndex);
454 entriesCO->blockSignals(false);
458 bool GuiCitation::isSelected(QModelIndex const & idx)
460 QString const str = idx.data().toString();
461 return selectedKeys().contains(str);
465 void GuiCitation::setButtons()
467 int const srows = selectedLV->model()->rowCount();
468 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(srows > 0);
469 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(srows > 0);
473 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
475 if (!idx.isValid() || bi.empty()) {
476 infoML->document()->clear();
477 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
481 infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
484 QString const keytxt = toqstr(
485 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), ci));
486 infoML->document()->setHtml(keytxt);
490 void GuiCitation::findText(QString const & text, bool reset)
492 //"All Fields" and "Keys" are the first two
493 int index = fieldsCO->currentIndex() - 2;
494 BiblioInfo const & bi = bibInfo();
495 vector<docstring> const & fields = bi.getFields();
498 if (index <= -1 || index >= int(fields.size()))
499 //either "All Fields" or "Keys" or an invalid value
500 field = from_ascii("");
502 field = fields[size_type(index)];
505 bool const onlyKeys = index == -1;
507 //"All Entry Types" is first.
508 index = entriesCO->currentIndex() - 1;
509 vector<docstring> const & entries = bi.getEntries();
510 docstring entry_type;
511 if (index < 0 || index >= int(entries.size()))
512 entry_type = from_ascii("");
514 entry_type = entries[size_type(index)];
516 bool const case_sentitive = casesense_->isChecked();
517 bool const reg_exp = regexp_->isChecked();
519 findKey(bi, text, onlyKeys, field, entry_type,
520 case_sentitive, reg_exp, reset);
522 //It'd be nice to save and restore the current selection in
523 //availableLV. Currently, we get an automatic reset, since the
530 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
532 findText(filter_->text(), true);
536 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
538 findText(filter_->text(), true);
542 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
544 if (index >= 0 && index < citationStyleCO->count()) {
545 vector<CitationStyle> const & styles = citeStyles_;
546 updateFormatting(styles[size_type(index)]);
552 void GuiCitation::filterChanged(const QString & text)
554 if (!text.isEmpty()) {
555 if (instant_->isChecked())
556 findText(filter_->text());
559 findText(filter_->text());
564 void GuiCitation::filterPressed()
566 findText(filter_->text(), true);
570 void GuiCitation::resetFilter()
572 filter_->setText(QString());
573 findText(filter_->text(), true);
577 void GuiCitation::caseChanged()
579 findText(filter_->text());
583 void GuiCitation::regexChanged()
585 findText(filter_->text());
589 void GuiCitation::updateFilterHint()
591 QString hint = instant_->isChecked() ?
592 qt_("Enter string to filter the list of available citations") :
593 qt_("Enter string to filter the list of available citations and press <Enter>");
594 hint += qt_("\nThe down arrow key will get you into the list of filtered citations.");
595 filter_->setToolTip(hint);
599 void GuiCitation::instantChanged(bool checked)
602 findText(filter_->text(), true);
608 void GuiCitation::changed()
614 void GuiCitation::applyParams(int const choice, bool full, bool force,
615 QString before, QString after)
617 if (cited_keys_.isEmpty())
620 vector<CitationStyle> const & styles = citeStyles_;
622 CitationStyle cs = styles[size_type(choice)];
629 cs.forceUpperCase &= force;
630 cs.hasStarredVersion &= full;
631 string const command = citationStyleToString(cs);
633 params_.setCmdName(command);
634 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
635 params_["before"] = qstring_to_ucs4(before);
636 params_["after"] = qstring_to_ucs4(after);
637 if (cs.hasQualifiedList) {
638 params_["pretextlist"] = getStringFromVector(getPreTexts(), from_ascii("\t"));
639 params_["posttextlist"] = getStringFromVector(getPostTexts(), from_ascii("\t"));
641 params_["literal"] = literalCB->isChecked() ? from_ascii("true") : from_ascii("false");
646 void GuiCitation::clearSelection()
649 setSelectedKeys(cited_keys_);
653 void GuiCitation::setSelectedKeys(QStringList const & sl)
655 selected_model_.clear();
656 selected_model_.setColumnCount(3);
658 headers << qt_("Text before")
660 << qt_("Text after");
661 selected_model_.setHorizontalHeaderLabels(headers);
662 selectedLV->setColumnHidden(0, true);
663 selectedLV->setColumnHidden(2, true);
664 selectedLV->verticalHeader()->setVisible(false);
665 selectedLV->horizontalHeader()->setVisible(false);
666 QStringList::const_iterator it = sl.begin();
667 QStringList::const_iterator end = sl.end();
668 for (int i = 0; it != end; ++it, ++i) {
669 QStandardItem * si = new QStandardItem();
673 si->setEditable(false);
674 selected_model_.setItem(i, 1, si);
679 QStringList GuiCitation::selectedKeys()
682 for (int i = 0; i != selected_model_.rowCount(); ++i) {
683 QStandardItem const * item = selected_model_.item(i, 1);
685 res.append(item->text());
691 void GuiCitation::setPreTexts(vector<docstring> const & m)
693 // account for multiple use of the same keys
694 QList<QModelIndex> handled;
695 for (docstring const & s: m) {
696 QStandardItem * si = new QStandardItem();
698 docstring pre = split(s, key, ' ');
699 si->setData(toqstr(pre));
700 si->setText(toqstr(pre));
701 QModelIndexList qmil =
702 selected_model_.match(selected_model_.index(0, 1),
703 Qt::DisplayRole, toqstr(key), -1,
704 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
705 for (auto const & idx : qmil) {
706 if (!handled.contains(idx)) {
707 selected_model_.setItem(idx.row(), 0, si);
716 vector<docstring> GuiCitation::getPreTexts()
718 vector<docstring> res;
719 for (int i = 0; i != selected_model_.rowCount(); ++i) {
720 QStandardItem const * key = selected_model_.item(i, 1);
721 QStandardItem const * pre = selected_model_.item(i, 0);
722 if (key && pre && !key->text().isEmpty())
723 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(pre->text()));
729 void GuiCitation::setPostTexts(vector<docstring> const & m)
731 // account for multiple use of the same keys
732 QList<QModelIndex> handled;
733 for (docstring const & s: m) {
734 QStandardItem * si = new QStandardItem();
736 docstring post = split(s, key, ' ');
737 si->setData(toqstr(post));
738 si->setText(toqstr(post));
739 QModelIndexList qmil =
740 selected_model_.match(selected_model_.index(0, 1),
741 Qt::DisplayRole, toqstr(key), -1,
742 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
743 for (auto const & idx : qmil) {
744 if (!handled.contains(idx)) {
745 selected_model_.setItem(idx.row(), 2, si);
754 vector<docstring> GuiCitation::getPostTexts()
756 vector<docstring> res;
757 for (int i = 0; i != selected_model_.rowCount(); ++i) {
758 QStandardItem const * key = selected_model_.item(i, 1);
759 QStandardItem const * post = selected_model_.item(i, 2);
760 if (key && post && !key->text().isEmpty())
761 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(post->text()));
767 void GuiCitation::init()
769 // Make the list of all available bibliography keys
770 BiblioInfo const & bi = bibInfo();
771 all_keys_ = to_qstring_list(bi.getKeys());
773 available_model_.setStringList(all_keys_);
775 // Ditto for the keys cited in this inset
776 QString str = toqstr(params_["key"]);
780 cited_keys_ = str.split(",");
781 setSelectedKeys(cited_keys_);
783 // Initialize the drop downs
787 // Initialize the citation formatting
788 string const & cmd = params_.getCmdName();
789 CitationStyle const cs =
790 citationStyleFromString(cmd, documentBuffer().params());
792 forceuppercaseCB->setChecked(cs.forceUpperCase);
793 starredCB->setChecked(cs.hasStarredVersion &&
794 documentBuffer().params().fullAuthorList());
795 textBeforeED->setText(toqstr(params_["before"]));
796 textAfterED->setText(toqstr(params_["after"]));
798 // if this is a new citation, we set the literal checkbox
799 // to its last set value.
800 if (cited_keys_.isEmpty())
801 literalCB->setChecked(InsetCitation::last_literal);
803 literalCB->setChecked(params_["literal"] == "true");
805 setPreTexts(getVectorFromString(params_["pretextlist"], from_ascii("\t")));
806 setPostTexts(getVectorFromString(params_["posttextlist"], from_ascii("\t")));
808 // Update the interface
811 if (selected_model_.rowCount()) {
812 selectedLV->blockSignals(true);
813 selectedLV->setFocus();
814 selectedLV->selectRow(0);
815 selectedLV->blockSignals(false);
817 // Find the citation style
818 vector<string> const & cmds = citeCmds_;
819 vector<string>::const_iterator cit =
820 std::find(cmds.begin(), cmds.end(), cs.name);
822 if (cit != cmds.end())
823 i = int(cit - cmds.begin());
825 // Set the style combo appropriately
826 citationStyleCO->blockSignals(true);
827 citationStyleCO->setCurrentIndex(i);
828 citationStyleCO->blockSignals(false);
829 updateFormatting(citeStyles_[size_type(i)]);
831 availableLV->setFocus();
833 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
834 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
838 void GuiCitation::findKey(BiblioInfo const & bi,
839 QString const & str, bool only_keys,
840 docstring field, docstring entry_type,
841 bool case_sensitive, bool reg_exp, bool reset)
844 // This should be moved to a class member.
845 // Used for optimisation: store last searched string.
846 static QString last_searched_string;
847 // Used to disable the above optimisation.
848 static bool last_case_sensitive;
849 static bool last_reg_exp;
850 // Reset last_searched_string in case of changed option.
851 if (last_case_sensitive != case_sensitive
852 || last_reg_exp != reg_exp) {
853 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
854 last_searched_string.clear();
856 // save option for next search.
857 last_case_sensitive = case_sensitive;
858 last_reg_exp = reg_exp;
860 Qt::CaseSensitivity qtcase = case_sensitive ?
861 Qt::CaseSensitive: Qt::CaseInsensitive;
863 // If new string (str) contains the last searched one...
865 !last_searched_string.isEmpty() &&
867 str.contains(last_searched_string, qtcase))
868 // ... then only search within already found list.
869 keys = available_model_.stringList();
871 // ... else search all keys.
873 // save searched string for next search.
874 last_searched_string = str;
878 // First, filter by entry_type, which will be faster than
879 // what follows, so we may get to do that on less.
880 vector<docstring> keyVector = to_docstring_vector(keys);
881 filterByEntryType(bi, keyVector, entry_type);
884 result = to_qstring_list(keyVector);
886 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
887 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
889 available_model_.setStringList(result);
893 BiblioInfo::CiteStringMap GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
895 vector<docstring> const keys = to_docstring_vector(cited_keys_);
896 vector<CitationStyle> styles = citeStyles_;
897 int ind = citationStyleCO->currentIndex();
900 CitationStyle cs = styles[size_type(ind)];
901 vector<docstring> pretexts = getPreTexts();
902 vector<docstring> posttexts = getPostTexts();
903 bool const qualified = cs.hasQualifiedList
904 && (selectedLV->model()->rowCount() > 1
906 || !posttexts.empty());
907 vector<pair<docstring, docstring>> pres;
908 for (docstring const & s: pretexts) {
910 docstring val = split(s, key, ' ');
911 pres.push_back(make_pair(key, val));
913 vector<pair<docstring, docstring>> posts;
914 for (docstring const & s: posttexts) {
916 docstring val = split(s, key, ' ');
917 posts.push_back(make_pair(key, val));
920 ci.textBefore = qstring_to_ucs4(textBeforeED->text());
921 ci.textAfter = qstring_to_ucs4(textAfterED->text());
922 ci.forceUpperCase = forceuppercaseCB->isChecked();
923 ci.Starred = starredCB->isChecked();
924 ci.context = CiteItem::Dialog;
925 ci.max_size = max_size;
926 ci.isQualified = qualified;
928 ci.posttexts = posts;
929 BiblioInfo::CiteStringMap ret = bi.getCiteStrings(keys, styles, documentBuffer(), ci);
934 void GuiCitation::setCitedKeys()
936 cited_keys_ = selectedKeys();
941 bool GuiCitation::initialiseParams(string const & sdata)
943 InsetCommand::string2params(sdata, params_);
944 citeCmds_ = documentBuffer().params().citeCommands();
945 citeStyles_ = documentBuffer().params().citeStyles();
951 void GuiCitation::clearParams()
957 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
958 vector<docstring> & keyVector, docstring entry_type)
960 if (entry_type.empty())
963 vector<docstring>::iterator it = keyVector.begin();
964 vector<docstring>::iterator end = keyVector.end();
966 vector<docstring> result;
967 for (; it != end; ++it) {
968 docstring const key = *it;
969 BiblioInfo::const_iterator cit = bi.find(key);
972 if (cit->second.entryType() == entry_type)
973 result.push_back(key);
979 // Escape special chars.
980 // All characters are literals except: '.|*?+(){}[]^$\'
981 // These characters are literals when preceded by a "\", which is done here
982 // @todo: This function should be moved to support, and then the test in tests
983 // should be moved there as well.
984 static docstring escape_special_chars(docstring const & expr)
986 // Search for all chars '.|*?+(){}[^$]\'
987 // Note that '[', ']', and '\' must be escaped.
988 static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
990 // $& is an ECMAScript format expression that expands to all
991 // of the current match
992 #ifdef LYX_USE_STD_REGEX
993 // To prefix a matched expression with a single literal backslash, we
994 // need to escape it for the C++ compiler and use:
996 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
998 // A backslash in the format string starts an escape sequence in boost.
999 // Thus, to prefix a matched expression with a single literal backslash,
1000 // we need to give two backslashes to the regex engine, and escape both
1001 // for the C++ compiler and use:
1003 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
1008 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
1009 vector<docstring> const & keys_to_search, bool only_keys,
1010 docstring const & search_expression, docstring field,
1011 bool case_sensitive, bool regex)
1013 vector<docstring> foundKeys;
1015 docstring expr = trim(search_expression);
1020 // We must escape special chars in the search_expr so that
1021 // it is treated as a simple string by lyx::regex.
1022 expr = escape_special_chars(expr);
1026 reg_exp.assign(to_utf8(expr), case_sensitive ?
1027 lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
1028 } catch (lyx::regex_error const & e) {
1029 // lyx::regex throws an exception if the regular expression is not
1031 LYXERR(Debug::GUI, e.what());
1032 return vector<docstring>();
1035 vector<docstring>::const_iterator it = keys_to_search.begin();
1036 vector<docstring>::const_iterator end = keys_to_search.end();
1037 for (; it != end; ++it ) {
1038 BiblioInfo::const_iterator info = bi.find(*it);
1039 if (info == bi.end())
1042 BibTeXInfo const & kvm = info->second;
1045 sdata = to_utf8(*it);
1046 else if (field.empty())
1047 sdata = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
1049 sdata = to_utf8(kvm[field]);
1055 if (lyx::regex_search(sdata, reg_exp))
1056 foundKeys.push_back(*it);
1058 catch (lyx::regex_error const & e) {
1059 LYXERR(Debug::GUI, e.what());
1060 return vector<docstring>();
1067 void GuiCitation::dispatchParams()
1069 std::string const lfun = InsetCommand::params2string(params_);
1070 dispatch(FuncRequest(getLfun(), lfun));
1074 BiblioInfo const & GuiCitation::bibInfo() const
1076 Buffer const & buf = documentBuffer();
1077 buf.reloadBibInfoCache();
1078 return buf.masterBibInfo();
1082 void GuiCitation::saveSession(QSettings & settings) const
1084 Dialog::saveSession(settings);
1086 sessionKey() + "/regex", regexp_->isChecked());
1088 sessionKey() + "/casesensitive", casesense_->isChecked());
1090 sessionKey() + "/autofind", instant_->isChecked());
1092 sessionKey() + "/citestyle", style_);
1094 sessionKey() + "/literal", InsetCitation::last_literal);
1098 void GuiCitation::restoreSession()
1100 Dialog::restoreSession();
1102 regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
1103 casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
1104 instant_->setChecked(settings.value(sessionKey() + "/autofind", true).toBool());
1105 style_ = settings.value(sessionKey() + "/citestyle").toString();
1106 InsetCitation::last_literal =
1107 settings.value(sessionKey() + "/literal", false).toBool();
1112 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
1115 } // namespace frontend
1118 #include "moc_GuiCitation.cpp"