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 "FancyLineEdit.h"
20 #include "GuiApplication.h"
21 #include "GuiSelectionManager.h"
22 #include "qt_helpers.h"
25 #include "BufferView.h"
26 #include "BufferParams.h"
28 #include "TextClass.h"
29 #include "FuncRequest.h"
31 #include "insets/InsetCitation.h"
32 #include "insets/InsetCommand.h"
34 #include "support/debug.h"
35 #include "support/docstring.h"
36 #include "support/gettext.h"
37 #include "support/lstrings.h"
39 #include <QCloseEvent>
43 #include <QStandardItemModel>
48 #include "support/regex.h"
55 using namespace lyx::support;
61 // I am guessing that it would not hurt to make these private members.
62 static vector<string> citeCmds_;
63 static vector<CitationStyle> citeStyles_;
66 template<typename String>
67 static QStringList to_qstring_list(vector<String> const & v)
71 for (size_t i = 0; i != v.size(); ++i) {
74 qlist.append(lyx::toqstr(v[i]));
80 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
82 vector<lyx::docstring> v;
83 for (int i = 0; i != qlist.size(); ++i) {
84 if (qlist[i].isEmpty())
86 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
92 GuiCitation::GuiCitation(GuiView & lv)
93 : DialogView(lv, "citation", qt_("Citation")),
94 style_(QString()), params_(insetCode("citation"))
99 filter_ = new FancyLineEdit(this);
100 filter_->setButtonPixmap(FancyLineEdit::Right, getPixmap("images/", "editclear", "svgz,png"));
101 filter_->setButtonVisible(FancyLineEdit::Right, true);
102 filter_->setButtonToolTip(FancyLineEdit::Right, qt_("Clear text"));
103 filter_->setAutoHideButton(FancyLineEdit::Right, true);
104 filter_->setPlaceholderText(qt_("All avail. citations"));
106 filterBarL->addWidget(filter_, 0);
107 findKeysLA->setBuddy(filter_);
109 // Add search options as button menu
110 regexp_ = new QAction(qt_("Regular e&xpression"), this);
111 regexp_->setCheckable(true);
112 casesense_ = new QAction(qt_("Case se&nsitive"), this);
113 casesense_->setCheckable(true);
114 instant_ = new QAction(qt_("Search as you &type"), this);
115 instant_->setCheckable(true);
116 instant_->setChecked(true);
118 QMenu * searchOpts = new QMenu(this);
119 searchOpts->addAction(regexp_);
120 searchOpts->addAction(casesense_);
121 searchOpts->addAction(instant_);
122 searchOptionsPB->setMenu(searchOpts);
124 connect(citationStyleCO, SIGNAL(activated(int)),
125 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
126 connect(starredCB, SIGNAL(clicked()),
127 this, SLOT(updateStyles()));
128 connect(literalCB, SIGNAL(clicked()),
129 this, SLOT(changed()));
130 connect(forceuppercaseCB, SIGNAL(clicked()),
131 this, SLOT(updateStyles()));
132 connect(textBeforeED, SIGNAL(textChanged(QString)),
133 this, SLOT(updateStyles()));
134 connect(textAfterED, SIGNAL(textChanged(QString)),
135 this, SLOT(updateStyles()));
136 connect(textBeforeED, SIGNAL(returnPressed()),
137 this, SLOT(on_buttonBox_accepted()));
138 connect(textAfterED, SIGNAL(returnPressed()),
139 this, SLOT(on_buttonBox_accepted()));
141 selectionManager = new GuiSelectionManager(this, availableLV, selectedLV,
142 addPB, deletePB, upPB, downPB, &available_model_, &selected_model_, 1);
143 connect(selectionManager, SIGNAL(selectionChanged()),
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, [=](){ 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);
203 void GuiCitation::showEvent(QShowEvent * e)
205 if (!filter_->text().isEmpty())
207 availableLV->setFocus();
208 DialogView::showEvent(e);
212 void GuiCitation::on_buttonBox_accepted()
220 void GuiCitation::on_buttonBox_rejected()
227 void GuiCitation::on_buttonBox_clicked(QAbstractButton * button)
229 switch (buttonBox->standardButton(button)) {
230 case QDialogButtonBox::Apply:
233 case QDialogButtonBox::Reset:
244 void GuiCitation::on_literalCB_clicked()
246 InsetCitation::last_literal = literalCB->isChecked();
251 void GuiCitation::updateControls()
253 BiblioInfo const & bi = bibInfo();
258 // The main point of separating this out is that the fill*() methods
259 // called in update() do not need to be called for INTERNAL updates,
260 // such as when addPB is pressed, as the list of fields, entries, etc,
261 // will not have changed.
262 void GuiCitation::updateControls(BiblioInfo const & bi)
264 QModelIndex idx = selectionManager->getSelectedIndex(1);
266 int i = citationStyleCO->currentIndex();
267 if (i == -1 || i > int(citeStyles_.size()))
269 updateFormatting(citeStyles_[size_type(i)]);
270 selectionManager->update();
274 void GuiCitation::updateFormatting(CitationStyle const & currentStyle)
276 BufferParams const bp = documentBuffer().params();
277 bool const force = currentStyle.forceUpperCase;
278 bool const starred = currentStyle.hasStarredVersion;
279 bool const full = starred && bp.fullAuthorList();
280 bool const textbefore = currentStyle.textBefore;
281 bool const textafter = currentStyle.textAfter;
283 int const rows = selectedLV->model()->rowCount();
285 bool const qualified = currentStyle.hasQualifiedList && rows > 0;
287 selectedLV->horizontalHeader()->setVisible(qualified);
288 selectedLV->setColumnHidden(0, !qualified);
289 selectedLV->setColumnHidden(2, !qualified);
290 bool const haveSelection = rows > 0;
292 textBeforeLA->setText(qt_("General text befo&re:"));
293 textAfterLA->setText(qt_("General &text after:"));
294 textBeforeED->setToolTip(qt_("Text that precedes the whole reference list. "
295 "For text that precedes individual items, "
296 "double-click on the respective entry above."));
297 textAfterLA->setToolTip(qt_("General &text after:"));
298 textAfterED->setToolTip(qt_("Text that follows the whole reference list. "
299 "For text that follows individual items, "
300 "double-click on the respective entry above."));
302 textBeforeLA->setText(qt_("Text befo&re:"));
303 if (textbefore && haveSelection)
304 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\")"));
306 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\"), "
307 "if the current citation style supports this."));
308 textAfterLA->setText(qt_("&Text after:"));
309 if (textafter && haveSelection)
310 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages)"));
312 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages), "
313 "if the current citation style supports this."));
316 forceuppercaseCB->setEnabled(force && haveSelection);
317 if (force && haveSelection)
318 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\")."));
320 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\"), "
321 "if the current citation style supports this."));
322 starredCB->setEnabled(full && haveSelection);
323 textBeforeED->setEnabled(textbefore && haveSelection);
324 textBeforeLA->setEnabled(textbefore && haveSelection);
325 textAfterED->setEnabled(textafter && haveSelection);
326 textAfterLA->setEnabled(textafter && haveSelection);
327 literalCB->setEnabled(textbefore || textafter);
328 citationStyleCO->setEnabled(haveSelection);
329 citationStyleLA->setEnabled(haveSelection);
331 // Check if we have a custom string/tooltip for the starred version
332 if (starred && !currentStyle.stardesc.empty()) {
334 bp.documentClass().getCiteMacro(bp.citeEngineType(), currentStyle.stardesc);
337 guistring = translateIfPossible(from_utf8(val));
338 starredCB->setText(toqstr(guistring));
339 starredCB->setEnabled(haveSelection);
341 if (!currentStyle.startooltip.empty()) {
342 val = bp.documentClass().getCiteMacro(bp.citeEngineType(),
343 currentStyle.startooltip);
345 guistring = translateIfPossible(from_utf8(val));
347 // Tooltip might also be empty
348 starredCB->setToolTip(toqstr(guistring));
350 // This is the default meaning of the starred commands
351 starredCB->setText(qt_("All aut&hors"));
352 if (full && haveSelection)
353 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\")"));
355 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\"), "
356 "if the current citation style supports this."));
358 if (availableLV->selectionModel()->selectedIndexes().isEmpty())
359 availableLV->setToolTip(qt_("All references available for citing."));
361 availableLV->setToolTip(qt_("All references available for citing.\n"
362 "To add the selected one, hit Add, press Enter or double-click.\n"
363 "Hit Ctrl-Enter to add and close the dialog."));
364 // With qualified citation lists, it makes sense to add the same key multiple times
365 selectionManager->allowMultiSelection(currentStyle.hasQualifiedList);
369 // Update the styles for the style combo, citationStyleCO, and mark the
370 // settings as changed. Called upon changing the cited keys (including
371 // merely reordering the keys) or editing the text before/after fields.
372 void GuiCitation::updateStyles()
374 BiblioInfo const & bi = bibInfo();
380 // Update the styles for the style combo, citationStyleCO.
381 void GuiCitation::updateStyles(BiblioInfo const & bi)
383 QStringList selected_keys = selectedKeys();
384 int curr = selectedLV->model()->rowCount() - 1;
386 if (curr < 0 || selected_keys.empty()) {
388 citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
389 citationStyleCO->clear();
390 citationStyleCO->setEnabled(false);
391 citationStyleLA->setEnabled(false);
395 static const size_t max_length = 80;
396 BiblioInfo::CiteStringMap sty = citationStyles(bi, max_length);
400 citationStyleCO->setEnabled(false);
401 citationStyleLA->setEnabled(false);
402 citationStyleCO->clear();
406 citationStyleCO->blockSignals(true);
408 // save old style selection
409 QString const curdata =
410 citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
411 QString const olddata = (curdata.isEmpty()) ?
412 (last_chosen_style_.isEmpty() ? style_ : last_chosen_style_): curdata;
414 last_chosen_style_.clear();
415 citationStyleCO->clear();
416 BiblioInfo::CiteStringMap::const_iterator cit = sty.begin();
417 BiblioInfo::CiteStringMap::const_iterator end = sty.end();
418 for (int ii = 1; cit != end; ++cit, ++ii)
419 citationStyleCO->addItem(toqstr(cit->second), toqstr(cit->first));
420 citationStyleCO->setEnabled(true);
421 citationStyleLA->setEnabled(true);
422 // restore old style selection
423 int const i = citationStyleCO->findData(olddata);
425 citationStyleCO->setCurrentIndex(i);
427 citationStyleCO->blockSignals(false);
431 void GuiCitation::fillFields(BiblioInfo const & bi)
433 fieldsCO->blockSignals(true);
434 int const oldIndex = fieldsCO->currentIndex();
436 QStringList const fields = to_qstring_list(bi.getFields());
437 fieldsCO->insertItem(0, qt_("All fields"));
438 fieldsCO->insertItem(1, qt_("Keys"));
439 fieldsCO->insertItems(2, fields);
440 if (oldIndex != -1 && oldIndex < fieldsCO->count())
441 fieldsCO->setCurrentIndex(oldIndex);
442 fieldsCO->blockSignals(false);
446 void GuiCitation::fillEntries(BiblioInfo const & bi)
448 entriesCO->blockSignals(true);
449 int const oldIndex = entriesCO->currentIndex();
451 QStringList const entries = to_qstring_list(bi.getEntries());
452 entriesCO->insertItem(0, qt_("All entry types"));
453 entriesCO->insertItems(1, entries);
454 if (oldIndex != -1 && oldIndex < entriesCO->count())
455 entriesCO->setCurrentIndex(oldIndex);
456 entriesCO->blockSignals(false);
460 bool GuiCitation::isSelected(QModelIndex const & idx)
462 QString const str = idx.data().toString();
463 return selectedKeys().contains(str);
467 void GuiCitation::setButtons()
469 int const srows = selectedLV->model()->rowCount();
470 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(srows > 0);
471 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(srows > 0);
475 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
477 if (!idx.isValid() || bi.empty()) {
478 infoML->document()->clear();
479 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
483 infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
486 QString const keytxt = toqstr(
487 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), ci));
488 infoML->document()->setHtml(keytxt);
492 void GuiCitation::findText(QString const & text, bool reset)
494 //"All Fields" and "Keys" are the first two
495 int index = fieldsCO->currentIndex() - 2;
496 BiblioInfo const & bi = bibInfo();
497 vector<docstring> const & fields = bi.getFields();
500 if (index <= -1 || index >= int(fields.size()))
501 //either "All Fields" or "Keys" or an invalid value
502 field = from_ascii("");
504 field = fields[size_type(index)];
507 bool const onlyKeys = index == -1;
509 //"All Entry Types" is first.
510 index = entriesCO->currentIndex() - 1;
511 vector<docstring> const & entries = bi.getEntries();
512 docstring entry_type;
513 if (index < 0 || index >= int(entries.size()))
514 entry_type = from_ascii("");
516 entry_type = entries[size_type(index)];
518 bool const case_sentitive = casesense_->isChecked();
519 bool const reg_exp = regexp_->isChecked();
521 findKey(bi, text, onlyKeys, field, entry_type,
522 case_sentitive, reg_exp, reset);
524 //It'd be nice to save and restore the current selection in
525 //availableLV. Currently, we get an automatic reset, since the
532 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
534 findText(filter_->text(), true);
538 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
540 findText(filter_->text(), true);
544 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
546 if (index >= 0 && index < citationStyleCO->count()) {
547 vector<CitationStyle> const & styles = citeStyles_;
548 updateFormatting(styles[size_type(index)]);
554 void GuiCitation::filterChanged(const QString & text)
556 if (!text.isEmpty()) {
557 if (instant_->isChecked())
558 findText(filter_->text());
561 findText(filter_->text());
566 void GuiCitation::filterPressed()
568 findText(filter_->text(), true);
572 void GuiCitation::resetFilter()
574 filter_->setText(QString());
575 findText(filter_->text(), true);
579 void GuiCitation::caseChanged()
581 findText(filter_->text());
585 void GuiCitation::regexChanged()
587 findText(filter_->text());
591 void GuiCitation::updateFilterHint()
593 QString hint = instant_->isChecked() ?
594 qt_("Enter string to filter the list of available citations") :
595 qt_("Enter string to filter the list of available citations and press <Enter>");
596 hint += qt_("\nThe down arrow key will get you into the list of filtered citations.");
597 filter_->setToolTip(hint);
601 void GuiCitation::instantChanged(bool checked)
604 findText(filter_->text(), true);
610 void GuiCitation::changed()
616 void GuiCitation::applyParams(int const choice, bool full, bool force,
617 QString before, QString after)
619 if (cited_keys_.isEmpty())
622 vector<CitationStyle> const & styles = citeStyles_;
624 CitationStyle cs = styles[size_type(choice)];
631 cs.forceUpperCase &= force;
632 cs.hasStarredVersion &= full;
633 string const command = citationStyleToString(cs);
635 params_.setCmdName(command);
636 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
637 params_["before"] = qstring_to_ucs4(before);
638 params_["after"] = qstring_to_ucs4(after);
639 if (cs.hasQualifiedList) {
640 params_["pretextlist"] = getStringFromVector(getPreTexts(), from_ascii("\t"));
641 params_["posttextlist"] = getStringFromVector(getPostTexts(), from_ascii("\t"));
643 params_["literal"] = literalCB->isChecked() ? from_ascii("true") : from_ascii("false");
648 void GuiCitation::clearSelection()
651 setSelectedKeys(cited_keys_);
655 void GuiCitation::setSelectedKeys(QStringList const & sl)
657 selected_model_.clear();
658 selected_model_.setColumnCount(3);
660 headers << qt_("Text before")
662 << qt_("Text after");
663 selected_model_.setHorizontalHeaderLabels(headers);
664 selectedLV->setColumnHidden(0, true);
665 selectedLV->setColumnHidden(2, true);
666 selectedLV->verticalHeader()->setVisible(false);
667 selectedLV->horizontalHeader()->setVisible(false);
668 QStringList::const_iterator it = sl.begin();
669 QStringList::const_iterator end = sl.end();
670 for (int i = 0; it != end; ++it, ++i) {
671 QStandardItem * si = new QStandardItem();
675 si->setEditable(false);
676 selected_model_.setItem(i, 1, si);
681 QStringList GuiCitation::selectedKeys()
684 for (int i = 0; i != selected_model_.rowCount(); ++i) {
685 QStandardItem const * item = selected_model_.item(i, 1);
687 res.append(item->text());
693 void GuiCitation::setPreTexts(vector<docstring> const & m)
695 // account for multiple use of the same keys
696 QList<QModelIndex> handled;
697 for (docstring const & s: m) {
698 QStandardItem * si = new QStandardItem();
700 docstring pre = split(s, key, ' ');
701 si->setData(toqstr(pre));
702 si->setText(toqstr(pre));
703 QModelIndexList qmil =
704 selected_model_.match(selected_model_.index(0, 1),
705 Qt::DisplayRole, toqstr(key), -1,
706 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
707 for (auto const & idx : qmil) {
708 if (!handled.contains(idx)) {
709 selected_model_.setItem(idx.row(), 0, si);
718 vector<docstring> GuiCitation::getPreTexts()
720 vector<docstring> res;
721 for (int i = 0; i != selected_model_.rowCount(); ++i) {
722 QStandardItem const * key = selected_model_.item(i, 1);
723 QStandardItem const * pre = selected_model_.item(i, 0);
724 if (key && pre && !key->text().isEmpty())
725 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(pre->text()));
731 void GuiCitation::setPostTexts(vector<docstring> const & m)
733 // account for multiple use of the same keys
734 QList<QModelIndex> handled;
735 for (docstring const & s: m) {
736 QStandardItem * si = new QStandardItem();
738 docstring post = split(s, key, ' ');
739 si->setData(toqstr(post));
740 si->setText(toqstr(post));
741 QModelIndexList qmil =
742 selected_model_.match(selected_model_.index(0, 1),
743 Qt::DisplayRole, toqstr(key), -1,
744 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
745 for (auto const & idx : qmil) {
746 if (!handled.contains(idx)) {
747 selected_model_.setItem(idx.row(), 2, si);
756 vector<docstring> GuiCitation::getPostTexts()
758 vector<docstring> res;
759 for (int i = 0; i != selected_model_.rowCount(); ++i) {
760 QStandardItem const * key = selected_model_.item(i, 1);
761 QStandardItem const * post = selected_model_.item(i, 2);
762 if (key && post && !key->text().isEmpty())
763 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(post->text()));
769 void GuiCitation::init()
771 // Make the list of all available bibliography keys
772 BiblioInfo const & bi = bibInfo();
773 all_keys_ = to_qstring_list(bi.getKeys());
775 available_model_.setStringList(all_keys_);
777 // Ditto for the keys cited in this inset
778 QString str = toqstr(params_["key"]);
782 cited_keys_ = str.split(",");
783 setSelectedKeys(cited_keys_);
785 // Initialize the drop downs
789 // Initialize the citation formatting
790 string const & cmd = params_.getCmdName();
791 CitationStyle const cs =
792 citationStyleFromString(cmd, documentBuffer().params());
794 forceuppercaseCB->setChecked(cs.forceUpperCase);
795 starredCB->setChecked(cs.hasStarredVersion &&
796 documentBuffer().params().fullAuthorList());
797 textBeforeED->setText(toqstr(params_["before"]));
798 textAfterED->setText(toqstr(params_["after"]));
800 // if this is a new citation, we set the literal checkbox
801 // to its last set value.
802 if (cited_keys_.isEmpty())
803 literalCB->setChecked(InsetCitation::last_literal);
805 literalCB->setChecked(params_["literal"] == "true");
807 setPreTexts(getVectorFromString(params_["pretextlist"], from_ascii("\t")));
808 setPostTexts(getVectorFromString(params_["posttextlist"], from_ascii("\t")));
810 // Update the interface
813 if (selected_model_.rowCount()) {
814 selectedLV->blockSignals(true);
815 selectedLV->setFocus();
816 selectedLV->selectRow(0);
817 selectedLV->blockSignals(false);
819 // Find the citation style
820 vector<string> const & cmds = citeCmds_;
821 vector<string>::const_iterator cit =
822 std::find(cmds.begin(), cmds.end(), cs.name);
824 if (cit != cmds.end())
825 i = int(cit - cmds.begin());
827 // Set the style combo appropriately
828 citationStyleCO->blockSignals(true);
829 citationStyleCO->setCurrentIndex(i);
830 citationStyleCO->blockSignals(false);
831 updateFormatting(citeStyles_[size_type(i)]);
833 availableLV->setFocus();
835 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
836 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
840 void GuiCitation::findKey(BiblioInfo const & bi,
841 QString const & str, bool only_keys,
842 docstring field, docstring entry_type,
843 bool case_sensitive, bool reg_exp, bool reset)
846 // This should be moved to a class member.
847 // Used for optimisation: store last searched string.
848 static QString last_searched_string;
849 // Used to disable the above optimisation.
850 static bool last_case_sensitive;
851 static bool last_reg_exp;
852 // Reset last_searched_string in case of changed option.
853 if (last_case_sensitive != case_sensitive
854 || last_reg_exp != reg_exp) {
855 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
856 last_searched_string.clear();
858 // save option for next search.
859 last_case_sensitive = case_sensitive;
860 last_reg_exp = reg_exp;
862 Qt::CaseSensitivity qtcase = case_sensitive ?
863 Qt::CaseSensitive: Qt::CaseInsensitive;
865 // If new string (str) contains the last searched one...
867 !last_searched_string.isEmpty() &&
869 str.contains(last_searched_string, qtcase))
870 // ... then only search within already found list.
871 keys = available_model_.stringList();
873 // ... else search all keys.
875 // save searched string for next search.
876 last_searched_string = str;
880 // First, filter by entry_type, which will be faster than
881 // what follows, so we may get to do that on less.
882 vector<docstring> keyVector = to_docstring_vector(keys);
883 filterByEntryType(bi, keyVector, entry_type);
886 result = to_qstring_list(keyVector);
888 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
889 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
891 available_model_.setStringList(result);
895 BiblioInfo::CiteStringMap GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
897 vector<docstring> const keys = to_docstring_vector(cited_keys_);
898 vector<CitationStyle> styles = citeStyles_;
899 int ind = citationStyleCO->currentIndex();
902 CitationStyle cs = styles[size_type(ind)];
903 vector<docstring> pretexts = getPreTexts();
904 vector<docstring> posttexts = getPostTexts();
905 bool const qualified = cs.hasQualifiedList
906 && (selectedLV->model()->rowCount() > 1
908 || !posttexts.empty());
909 vector<pair<docstring, docstring>> pres;
910 for (docstring const & s: pretexts) {
912 docstring val = split(s, key, ' ');
913 pres.push_back(make_pair(key, val));
915 vector<pair<docstring, docstring>> posts;
916 for (docstring const & s: posttexts) {
918 docstring val = split(s, key, ' ');
919 posts.push_back(make_pair(key, val));
922 ci.textBefore = qstring_to_ucs4(textBeforeED->text());
923 ci.textAfter = qstring_to_ucs4(textAfterED->text());
924 ci.forceUpperCase = forceuppercaseCB->isChecked();
925 ci.Starred = starredCB->isChecked();
926 ci.context = CiteItem::Dialog;
927 ci.max_size = max_size;
928 ci.isQualified = qualified;
930 ci.posttexts = posts;
931 BiblioInfo::CiteStringMap ret = bi.getCiteStrings(keys, styles, documentBuffer(), ci);
936 void GuiCitation::setCitedKeys()
938 cited_keys_ = selectedKeys();
943 bool GuiCitation::initialiseParams(string const & sdata)
945 InsetCommand::string2params(sdata, params_);
946 citeCmds_ = documentBuffer().params().citeCommands();
947 citeStyles_ = documentBuffer().params().citeStyles();
953 void GuiCitation::clearParams()
959 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
960 vector<docstring> & keyVector, docstring const & entry_type)
962 if (entry_type.empty())
965 vector<docstring>::iterator it = keyVector.begin();
966 vector<docstring>::iterator end = keyVector.end();
968 vector<docstring> result;
969 for (; it != end; ++it) {
970 docstring const key = *it;
971 BiblioInfo::const_iterator cit = bi.find(key);
974 if (cit->second.entryType() == entry_type)
975 result.push_back(key);
981 // Escape special chars.
982 // All characters are literals except: '.|*?+(){}[]^$\'
983 // These characters are literals when preceded by a "\", which is done here
984 // @todo: This function should be moved to support, and then the test in tests
985 // should be moved there as well.
986 static docstring escape_special_chars(docstring const & expr)
988 // Search for all chars '.|*?+(){}[^$]\'
989 // Note that '[', ']', and '\' must be escaped.
990 static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
992 // $& is an ECMAScript format expression that expands to all
993 // of the current match
994 // To prefix a matched expression with a single literal backslash, we
995 // need to escape it for the C++ compiler and use:
997 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
1001 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
1002 vector<docstring> const & keys_to_search, bool only_keys,
1003 docstring const & search_expression, docstring const & field,
1004 bool case_sensitive, bool regex)
1006 vector<docstring> foundKeys;
1008 docstring expr = trim(search_expression);
1013 // We must escape special chars in the search_expr so that
1014 // it is treated as a simple string by lyx::regex.
1015 expr = escape_special_chars(expr);
1019 reg_exp.assign(to_utf8(expr), case_sensitive ?
1020 lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
1021 } catch (lyx::regex_error const & e) {
1022 // lyx::regex throws an exception if the regular expression is not
1024 LYXERR(Debug::GUI, e.what());
1025 return vector<docstring>();
1028 vector<docstring>::const_iterator it = keys_to_search.begin();
1029 vector<docstring>::const_iterator end = keys_to_search.end();
1030 for (; it != end; ++it ) {
1031 BiblioInfo::const_iterator info = bi.find(*it);
1032 if (info == bi.end())
1035 BibTeXInfo const & kvm = info->second;
1038 sdata = to_utf8(*it);
1039 else if (field.empty())
1040 sdata = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
1042 sdata = to_utf8(kvm[field]);
1048 if (lyx::regex_search(sdata, reg_exp))
1049 foundKeys.push_back(*it);
1051 catch (lyx::regex_error const & e) {
1052 LYXERR(Debug::GUI, e.what());
1053 return vector<docstring>();
1060 void GuiCitation::dispatchParams()
1062 std::string const lfun = InsetCommand::params2string(params_);
1063 dispatch(FuncRequest(getLfun(), lfun));
1067 BiblioInfo const & GuiCitation::bibInfo() const
1069 Buffer const & buf = documentBuffer();
1070 buf.reloadBibInfoCache();
1071 return buf.masterBibInfo();
1075 void GuiCitation::saveSession(QSettings & settings) const
1077 Dialog::saveSession(settings);
1079 sessionKey() + "/regex", regexp_->isChecked());
1081 sessionKey() + "/casesensitive", casesense_->isChecked());
1083 sessionKey() + "/autofind", instant_->isChecked());
1085 sessionKey() + "/citestyle", style_);
1087 sessionKey() + "/literal", InsetCitation::last_literal);
1091 void GuiCitation::restoreSession()
1093 Dialog::restoreSession();
1095 regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
1096 casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
1097 instant_->setChecked(settings.value(sessionKey() + "/autofind", true).toBool());
1098 style_ = settings.value(sessionKey() + "/citestyle").toString();
1099 InsetCitation::last_literal =
1100 settings.value(sessionKey() + "/literal", false).toBool();
1105 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
1108 } // namespace frontend
1111 #include "moc_GuiCitation.cpp"