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"
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>
54 using namespace lyx::support;
60 // I am guessing that it would not hurt to make these private members.
61 static vector<string> citeCmds_;
62 static vector<CitationStyle> citeStyles_;
65 template<typename String>
66 static QStringList to_qstring_list(vector<String> const & v)
70 for (size_t i = 0; i != v.size(); ++i) {
73 qlist.append(lyx::toqstr(v[i]));
79 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
81 vector<lyx::docstring> v;
82 for (int i = 0; i != qlist.size(); ++i) {
83 if (qlist[i].isEmpty())
85 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
91 GuiCitation::GuiCitation(GuiView & lv)
92 : DialogView(lv, "citation", qt_("Citation")),
93 style_(QString()), params_(insetCode("citation"))
98 filter_ = new FancyLineEdit(this);
99 filter_->setButtonPixmap(FancyLineEdit::Right, getPixmap("images/", "editclear", "svgz,png"));
100 filter_->setButtonVisible(FancyLineEdit::Right, true);
101 filter_->setButtonToolTip(FancyLineEdit::Right, qt_("Clear text"));
102 filter_->setAutoHideButton(FancyLineEdit::Right, true);
103 filter_->setPlaceholderText(qt_("All avail. citations"));
105 filterBarL->addWidget(filter_, 0);
106 findKeysLA->setBuddy(filter_);
108 // Add search options as button menu
109 regexp_ = new QAction(qt_("Regular e&xpression"), this);
110 regexp_->setCheckable(true);
111 casesense_ = new QAction(qt_("Case se&nsitive"), this);
112 casesense_->setCheckable(true);
113 instant_ = new QAction(qt_("Search as you &type"), this);
114 instant_->setCheckable(true);
115 instant_->setChecked(true);
117 QMenu * searchOpts = new QMenu(this);
118 searchOpts->addAction(regexp_);
119 searchOpts->addAction(casesense_);
120 searchOpts->addAction(instant_);
121 searchOptionsPB->setMenu(searchOpts);
123 connect(citationStyleCO, SIGNAL(activated(int)),
124 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
125 connect(starredCB, SIGNAL(clicked()),
126 this, SLOT(updateStyles()));
127 connect(literalCB, SIGNAL(clicked()),
128 this, SLOT(changed()));
129 connect(forceuppercaseCB, SIGNAL(clicked()),
130 this, SLOT(updateStyles()));
131 connect(textBeforeED, SIGNAL(textChanged(QString)),
132 this, SLOT(updateStyles()));
133 connect(textAfterED, SIGNAL(textChanged(QString)),
134 this, SLOT(updateStyles()));
135 connect(textBeforeED, SIGNAL(returnPressed()),
136 this, SLOT(on_buttonBox_accepted()));
137 connect(textAfterED, SIGNAL(returnPressed()),
138 this, SLOT(on_buttonBox_accepted()));
140 selectionManager = new GuiSelectionManager(this, availableLV, selectedLV,
141 addPB, deletePB, upPB, downPB, &available_model_, &selected_model_, 1);
142 connect(selectionManager, SIGNAL(selectionChanged()),
143 this, SLOT(setCitedKeys()));
144 connect(selectionManager, SIGNAL(updateHook()),
145 this, SLOT(updateControls()));
146 connect(selectionManager, SIGNAL(okHook()),
147 this, SLOT(on_buttonBox_accepted()));
149 connect(filter_, SIGNAL(rightButtonClicked()),
150 this, SLOT(resetFilter()));
151 connect(filter_, SIGNAL(textEdited(QString)),
152 this, SLOT(filterChanged(QString)));
153 connect(filter_, SIGNAL(returnPressed()),
154 this, SLOT(filterPressed()));
155 #if (QT_VERSION < 0x050000)
156 connect(filter_, SIGNAL(downPressed()),
157 availableLV, SLOT(setFocus()));
159 connect(filter_, &FancyLineEdit::downPressed,
160 availableLV, [=](){ focusAndHighlight(availableLV); });
162 connect(regexp_, SIGNAL(triggered()),
163 this, SLOT(regexChanged()));
164 connect(casesense_, SIGNAL(triggered()),
165 this, SLOT(caseChanged()));
166 connect(instant_, SIGNAL(triggered(bool)),
167 this, SLOT(instantChanged(bool)));
169 #if (QT_VERSION < 0x050000)
170 selectedLV->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
172 selectedLV->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
175 selectedLV->setToolTip(qt_("Ordered list of all cited references.\n"
176 "You can reorder, add and remove references with the buttons on the left."));
177 setFocusProxy(filter_);
181 void GuiCitation::closeEvent(QCloseEvent * e)
184 DialogView::closeEvent(e);
188 void GuiCitation::applyView()
190 int const choice = max(0, citationStyleCO->currentIndex());
191 style_ = citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
192 bool const full = starredCB->isChecked();
193 bool const force = forceuppercaseCB->isChecked();
195 QString const before = textBeforeED->text();
196 QString const after = textAfterED->text();
198 applyParams(choice, full, force, before, after);
202 void GuiCitation::showEvent(QShowEvent * e)
204 if (!filter_->text().isEmpty())
206 availableLV->setFocus();
207 DialogView::showEvent(e);
211 void GuiCitation::on_buttonBox_accepted()
219 void GuiCitation::on_buttonBox_rejected()
226 void GuiCitation::on_buttonBox_clicked(QAbstractButton * button)
228 switch (buttonBox->standardButton(button)) {
229 case QDialogButtonBox::Apply:
232 case QDialogButtonBox::Reset:
243 void GuiCitation::on_literalCB_clicked()
245 InsetCitation::last_literal = literalCB->isChecked();
250 void GuiCitation::updateControls()
252 BiblioInfo const & bi = bibInfo();
257 // The main point of separating this out is that the fill*() methods
258 // called in update() do not need to be called for INTERNAL updates,
259 // such as when addPB is pressed, as the list of fields, entries, etc,
260 // will not have changed.
261 void GuiCitation::updateControls(BiblioInfo const & bi)
263 QModelIndex idx = selectionManager->getSelectedIndex(1);
265 int i = citationStyleCO->currentIndex();
266 if (i == -1 || i > int(citeStyles_.size()))
268 updateFormatting(citeStyles_[size_type(i)]);
269 selectionManager->update();
273 void GuiCitation::updateFormatting(CitationStyle const & currentStyle)
275 BufferParams const bp = documentBuffer().params();
276 bool const force = currentStyle.forceUpperCase;
277 bool const starred = currentStyle.hasStarredVersion;
278 bool const full = starred && bp.fullAuthorList();
279 bool const textbefore = currentStyle.textBefore;
280 bool const textafter = currentStyle.textAfter;
282 int const rows = selectedLV->model()->rowCount();
284 bool const qualified = currentStyle.hasQualifiedList && rows > 0;
286 selectedLV->horizontalHeader()->setVisible(qualified);
287 selectedLV->setColumnHidden(0, !qualified);
288 selectedLV->setColumnHidden(2, !qualified);
289 bool const haveSelection = rows > 0;
291 textBeforeLA->setText(qt_("General text befo&re:"));
292 textAfterLA->setText(qt_("General &text after:"));
293 textBeforeED->setToolTip(qt_("Text that precedes the whole reference list. "
294 "For text that precedes individual items, "
295 "double-click on the respective entry above."));
296 textAfterLA->setToolTip(qt_("General &text after:"));
297 textAfterED->setToolTip(qt_("Text that follows the whole reference list. "
298 "For text that follows individual items, "
299 "double-click on the respective entry above."));
301 textBeforeLA->setText(qt_("Text befo&re:"));
302 if (textbefore && haveSelection)
303 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\")"));
305 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\"), "
306 "if the current citation style supports this."));
307 textAfterLA->setText(qt_("&Text after:"));
308 if (textafter && haveSelection)
309 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages)"));
311 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages), "
312 "if the current citation style supports this."));
315 forceuppercaseCB->setEnabled(force && haveSelection);
316 if (force && haveSelection)
317 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\")."));
319 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\"), "
320 "if the current citation style supports this."));
321 starredCB->setEnabled(full && haveSelection);
322 textBeforeED->setEnabled(textbefore && haveSelection);
323 textBeforeLA->setEnabled(textbefore && haveSelection);
324 textAfterED->setEnabled(textafter && haveSelection);
325 textAfterLA->setEnabled(textafter && haveSelection);
326 literalCB->setEnabled(textbefore || textafter);
327 citationStyleCO->setEnabled(haveSelection);
328 citationStyleLA->setEnabled(haveSelection);
330 // Check if we have a custom string/tooltip for the starred version
331 if (starred && !currentStyle.stardesc.empty()) {
333 bp.documentClass().getCiteMacro(bp.citeEngineType(), currentStyle.stardesc);
336 guistring = translateIfPossible(from_utf8(val));
337 starredCB->setText(toqstr(guistring));
338 starredCB->setEnabled(haveSelection);
340 if (!currentStyle.startooltip.empty()) {
341 val = bp.documentClass().getCiteMacro(bp.citeEngineType(),
342 currentStyle.startooltip);
344 guistring = translateIfPossible(from_utf8(val));
346 // Tooltip might also be empty
347 starredCB->setToolTip(toqstr(guistring));
349 // This is the default meaning of the starred commands
350 starredCB->setText(qt_("All aut&hors"));
351 if (full && haveSelection)
352 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\")"));
354 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\"), "
355 "if the current citation style supports this."));
357 if (availableLV->selectionModel()->selectedIndexes().isEmpty())
358 availableLV->setToolTip(qt_("All references available for citing."));
360 availableLV->setToolTip(qt_("All references available for citing.\n"
361 "To add the selected one, hit Add, press Enter or double-click.\n"
362 "Hit Ctrl-Enter to add and close the dialog."));
363 // With qualified citation lists, it makes sense to add the same key multiple times
364 selectionManager->allowMultiSelection(currentStyle.hasQualifiedList);
368 // Update the styles for the style combo, citationStyleCO, and mark the
369 // settings as changed. Called upon changing the cited keys (including
370 // merely reordering the keys) or editing the text before/after fields.
371 void GuiCitation::updateStyles()
373 BiblioInfo const & bi = bibInfo();
379 // Update the styles for the style combo, citationStyleCO.
380 void GuiCitation::updateStyles(BiblioInfo const & bi)
382 QStringList selected_keys = selectedKeys();
383 int curr = selectedLV->model()->rowCount() - 1;
385 if (curr < 0 || selected_keys.empty()) {
387 citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
388 citationStyleCO->clear();
389 citationStyleCO->setEnabled(false);
390 citationStyleLA->setEnabled(false);
394 static const size_t max_length = 80;
395 BiblioInfo::CiteStringMap sty = citationStyles(bi, max_length);
399 citationStyleCO->setEnabled(false);
400 citationStyleLA->setEnabled(false);
401 citationStyleCO->clear();
405 citationStyleCO->blockSignals(true);
407 // save old style selection
408 QString const curdata =
409 citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
410 QString const olddata = (curdata.isEmpty()) ?
411 (last_chosen_style_.isEmpty() ? style_ : last_chosen_style_): curdata;
413 last_chosen_style_.clear();
414 citationStyleCO->clear();
415 BiblioInfo::CiteStringMap::const_iterator cit = sty.begin();
416 BiblioInfo::CiteStringMap::const_iterator end = sty.end();
417 for (int ii = 1; cit != end; ++cit, ++ii)
418 citationStyleCO->addItem(toqstr(cit->second), toqstr(cit->first));
419 citationStyleCO->setEnabled(true);
420 citationStyleLA->setEnabled(true);
421 // restore old style selection
422 int const i = citationStyleCO->findData(olddata);
424 citationStyleCO->setCurrentIndex(i);
426 citationStyleCO->blockSignals(false);
430 void GuiCitation::fillFields(BiblioInfo const & bi)
432 fieldsCO->blockSignals(true);
433 int const oldIndex = fieldsCO->currentIndex();
435 QStringList const fields = to_qstring_list(bi.getFields());
436 fieldsCO->insertItem(0, qt_("All fields"));
437 fieldsCO->insertItem(1, qt_("Keys"));
438 fieldsCO->insertItems(2, fields);
439 if (oldIndex != -1 && oldIndex < fieldsCO->count())
440 fieldsCO->setCurrentIndex(oldIndex);
441 fieldsCO->blockSignals(false);
445 void GuiCitation::fillEntries(BiblioInfo const & bi)
447 entriesCO->blockSignals(true);
448 int const oldIndex = entriesCO->currentIndex();
450 QStringList const entries = to_qstring_list(bi.getEntries());
451 entriesCO->insertItem(0, qt_("All entry types"));
452 entriesCO->insertItems(1, entries);
453 if (oldIndex != -1 && oldIndex < entriesCO->count())
454 entriesCO->setCurrentIndex(oldIndex);
455 entriesCO->blockSignals(false);
459 bool GuiCitation::isSelected(QModelIndex const & idx)
461 QString const str = idx.data().toString();
462 return selectedKeys().contains(str);
466 void GuiCitation::setButtons()
468 int const srows = selectedLV->model()->rowCount();
469 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(srows > 0);
470 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(srows > 0);
474 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
476 if (!idx.isValid() || bi.empty()) {
477 infoML->document()->clear();
478 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
482 infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
485 QString const keytxt = toqstr(
486 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), ci));
487 infoML->document()->setHtml(keytxt);
491 void GuiCitation::findText(QString const & text, bool reset)
493 //"All Fields" and "Keys" are the first two
494 int index = fieldsCO->currentIndex() - 2;
495 BiblioInfo const & bi = bibInfo();
496 vector<docstring> const & fields = bi.getFields();
499 if (index <= -1 || index >= int(fields.size()))
500 //either "All Fields" or "Keys" or an invalid value
501 field = from_ascii("");
503 field = fields[size_type(index)];
506 bool const onlyKeys = index == -1;
508 //"All Entry Types" is first.
509 index = entriesCO->currentIndex() - 1;
510 vector<docstring> const & entries = bi.getEntries();
511 docstring entry_type;
512 if (index < 0 || index >= int(entries.size()))
513 entry_type = from_ascii("");
515 entry_type = entries[size_type(index)];
517 bool const case_sentitive = casesense_->isChecked();
518 bool const reg_exp = regexp_->isChecked();
520 findKey(bi, text, onlyKeys, field, entry_type,
521 case_sentitive, reg_exp, reset);
523 //It'd be nice to save and restore the current selection in
524 //availableLV. Currently, we get an automatic reset, since the
531 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
533 findText(filter_->text(), true);
537 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
539 findText(filter_->text(), true);
543 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
545 if (index >= 0 && index < citationStyleCO->count()) {
546 vector<CitationStyle> const & styles = citeStyles_;
547 updateFormatting(styles[size_type(index)]);
553 void GuiCitation::filterChanged(const QString & text)
555 if (!text.isEmpty()) {
556 if (instant_->isChecked())
557 findText(filter_->text());
560 findText(filter_->text());
565 void GuiCitation::filterPressed()
567 findText(filter_->text(), true);
571 void GuiCitation::resetFilter()
573 filter_->setText(QString());
574 findText(filter_->text(), true);
578 void GuiCitation::caseChanged()
580 findText(filter_->text());
584 void GuiCitation::regexChanged()
586 findText(filter_->text());
590 void GuiCitation::updateFilterHint()
592 QString hint = instant_->isChecked() ?
593 qt_("Enter string to filter the list of available citations") :
594 qt_("Enter string to filter the list of available citations and press <Enter>");
595 hint += qt_("\nThe down arrow key will get you into the list of filtered citations.");
596 filter_->setToolTip(hint);
600 void GuiCitation::instantChanged(bool checked)
603 findText(filter_->text(), true);
609 void GuiCitation::changed()
615 void GuiCitation::applyParams(int const choice, bool full, bool force,
616 QString before, QString after)
618 if (cited_keys_.isEmpty())
621 vector<CitationStyle> const & styles = citeStyles_;
623 CitationStyle cs = styles[size_type(choice)];
630 cs.forceUpperCase &= force;
631 cs.hasStarredVersion &= full;
632 string const command = citationStyleToString(cs);
634 params_.setCmdName(command);
635 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
636 params_["before"] = qstring_to_ucs4(before);
637 params_["after"] = qstring_to_ucs4(after);
638 if (cs.hasQualifiedList) {
639 params_["pretextlist"] = getStringFromVector(getPreTexts(), from_ascii("\t"));
640 params_["posttextlist"] = getStringFromVector(getPostTexts(), from_ascii("\t"));
642 params_["literal"] = literalCB->isChecked() ? from_ascii("true") : from_ascii("false");
647 void GuiCitation::clearSelection()
650 setSelectedKeys(cited_keys_);
654 void GuiCitation::setSelectedKeys(QStringList const & sl)
656 selected_model_.clear();
657 selected_model_.setColumnCount(3);
659 headers << qt_("Text before")
661 << qt_("Text after");
662 selected_model_.setHorizontalHeaderLabels(headers);
663 selectedLV->setColumnHidden(0, true);
664 selectedLV->setColumnHidden(2, true);
665 selectedLV->verticalHeader()->setVisible(false);
666 selectedLV->horizontalHeader()->setVisible(false);
667 QStringList::const_iterator it = sl.begin();
668 QStringList::const_iterator end = sl.end();
669 for (int i = 0; it != end; ++it, ++i) {
670 QStandardItem * si = new QStandardItem();
674 si->setEditable(false);
675 selected_model_.setItem(i, 1, si);
680 QStringList GuiCitation::selectedKeys()
683 for (int i = 0; i != selected_model_.rowCount(); ++i) {
684 QStandardItem const * item = selected_model_.item(i, 1);
686 res.append(item->text());
692 void GuiCitation::setPreTexts(vector<docstring> const & m)
694 // account for multiple use of the same keys
695 QList<QModelIndex> handled;
696 for (docstring const & s: m) {
697 QStandardItem * si = new QStandardItem();
699 docstring pre = split(s, key, ' ');
700 si->setData(toqstr(pre));
701 si->setText(toqstr(pre));
702 QModelIndexList qmil =
703 selected_model_.match(selected_model_.index(0, 1),
704 Qt::DisplayRole, toqstr(key), -1,
705 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
706 for (auto const & idx : qmil) {
707 if (!handled.contains(idx)) {
708 selected_model_.setItem(idx.row(), 0, si);
717 vector<docstring> GuiCitation::getPreTexts()
719 vector<docstring> res;
720 for (int i = 0; i != selected_model_.rowCount(); ++i) {
721 QStandardItem const * key = selected_model_.item(i, 1);
722 QStandardItem const * pre = selected_model_.item(i, 0);
723 if (key && pre && !key->text().isEmpty())
724 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(pre->text()));
730 void GuiCitation::setPostTexts(vector<docstring> const & m)
732 // account for multiple use of the same keys
733 QList<QModelIndex> handled;
734 for (docstring const & s: m) {
735 QStandardItem * si = new QStandardItem();
737 docstring post = split(s, key, ' ');
738 si->setData(toqstr(post));
739 si->setText(toqstr(post));
740 QModelIndexList qmil =
741 selected_model_.match(selected_model_.index(0, 1),
742 Qt::DisplayRole, toqstr(key), -1,
743 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
744 for (auto const & idx : qmil) {
745 if (!handled.contains(idx)) {
746 selected_model_.setItem(idx.row(), 2, si);
755 vector<docstring> GuiCitation::getPostTexts()
757 vector<docstring> res;
758 for (int i = 0; i != selected_model_.rowCount(); ++i) {
759 QStandardItem const * key = selected_model_.item(i, 1);
760 QStandardItem const * post = selected_model_.item(i, 2);
761 if (key && post && !key->text().isEmpty())
762 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(post->text()));
768 void GuiCitation::init()
770 // Make the list of all available bibliography keys
771 BiblioInfo const & bi = bibInfo();
772 all_keys_ = to_qstring_list(bi.getKeys());
774 available_model_.setStringList(all_keys_);
776 // Ditto for the keys cited in this inset
777 QString str = toqstr(params_["key"]);
781 cited_keys_ = str.split(",");
782 setSelectedKeys(cited_keys_);
784 // Initialize the drop downs
788 // Initialize the citation formatting
789 string const & cmd = params_.getCmdName();
790 CitationStyle const cs =
791 citationStyleFromString(cmd, documentBuffer().params());
793 forceuppercaseCB->setChecked(cs.forceUpperCase);
794 starredCB->setChecked(cs.hasStarredVersion &&
795 documentBuffer().params().fullAuthorList());
796 textBeforeED->setText(toqstr(params_["before"]));
797 textAfterED->setText(toqstr(params_["after"]));
799 // if this is a new citation, we set the literal checkbox
800 // to its last set value.
801 if (cited_keys_.isEmpty())
802 literalCB->setChecked(InsetCitation::last_literal);
804 literalCB->setChecked(params_["literal"] == "true");
806 setPreTexts(getVectorFromString(params_["pretextlist"], from_ascii("\t")));
807 setPostTexts(getVectorFromString(params_["posttextlist"], from_ascii("\t")));
809 // Update the interface
812 if (selected_model_.rowCount()) {
813 selectedLV->blockSignals(true);
814 selectedLV->setFocus();
815 selectedLV->selectRow(0);
816 selectedLV->blockSignals(false);
818 // Find the citation style
819 vector<string> const & cmds = citeCmds_;
820 vector<string>::const_iterator cit =
821 std::find(cmds.begin(), cmds.end(), cs.name);
823 if (cit != cmds.end())
824 i = int(cit - cmds.begin());
826 // Set the style combo appropriately
827 citationStyleCO->blockSignals(true);
828 citationStyleCO->setCurrentIndex(i);
829 citationStyleCO->blockSignals(false);
830 updateFormatting(citeStyles_[size_type(i)]);
832 availableLV->setFocus();
834 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
835 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
839 void GuiCitation::findKey(BiblioInfo const & bi,
840 QString const & str, bool only_keys,
841 docstring field, docstring entry_type,
842 bool case_sensitive, bool reg_exp, bool reset)
845 // This should be moved to a class member.
846 // Used for optimisation: store last searched string.
847 static QString last_searched_string;
848 // Used to disable the above optimisation.
849 static bool last_case_sensitive;
850 static bool last_reg_exp;
851 // Reset last_searched_string in case of changed option.
852 if (last_case_sensitive != case_sensitive
853 || last_reg_exp != reg_exp) {
854 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
855 last_searched_string.clear();
857 // save option for next search.
858 last_case_sensitive = case_sensitive;
859 last_reg_exp = reg_exp;
861 Qt::CaseSensitivity qtcase = case_sensitive ?
862 Qt::CaseSensitive: Qt::CaseInsensitive;
864 // If new string (str) contains the last searched one...
866 !last_searched_string.isEmpty() &&
868 str.contains(last_searched_string, qtcase))
869 // ... then only search within already found list.
870 keys = available_model_.stringList();
872 // ... else search all keys.
874 // save searched string for next search.
875 last_searched_string = str;
879 // First, filter by entry_type, which will be faster than
880 // what follows, so we may get to do that on less.
881 vector<docstring> keyVector = to_docstring_vector(keys);
882 filterByEntryType(bi, keyVector, entry_type);
885 result = to_qstring_list(keyVector);
887 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
888 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
890 available_model_.setStringList(result);
894 BiblioInfo::CiteStringMap GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
896 vector<docstring> const keys = to_docstring_vector(cited_keys_);
897 vector<CitationStyle> styles = citeStyles_;
898 int ind = citationStyleCO->currentIndex();
901 CitationStyle cs = styles[size_type(ind)];
902 vector<docstring> pretexts = getPreTexts();
903 vector<docstring> posttexts = getPostTexts();
904 bool const qualified = cs.hasQualifiedList
905 && (selectedLV->model()->rowCount() > 1
907 || !posttexts.empty());
908 vector<pair<docstring, docstring>> pres;
909 for (docstring const & s: pretexts) {
911 docstring val = split(s, key, ' ');
912 pres.push_back(make_pair(key, val));
914 vector<pair<docstring, docstring>> posts;
915 for (docstring const & s: posttexts) {
917 docstring val = split(s, key, ' ');
918 posts.push_back(make_pair(key, val));
921 ci.textBefore = qstring_to_ucs4(textBeforeED->text());
922 ci.textAfter = qstring_to_ucs4(textAfterED->text());
923 ci.forceUpperCase = forceuppercaseCB->isChecked();
924 ci.Starred = starredCB->isChecked();
925 ci.context = CiteItem::Dialog;
926 ci.max_size = max_size;
927 ci.isQualified = qualified;
929 ci.posttexts = posts;
930 BiblioInfo::CiteStringMap ret = bi.getCiteStrings(keys, styles, documentBuffer(), ci);
935 void GuiCitation::setCitedKeys()
937 cited_keys_ = selectedKeys();
942 bool GuiCitation::initialiseParams(string const & sdata)
944 InsetCommand::string2params(sdata, params_);
945 citeCmds_ = documentBuffer().params().citeCommands();
946 citeStyles_ = documentBuffer().params().citeStyles();
952 void GuiCitation::clearParams()
958 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
959 vector<docstring> & keyVector, docstring const & entry_type)
961 if (entry_type.empty())
964 vector<docstring>::iterator it = keyVector.begin();
965 vector<docstring>::iterator end = keyVector.end();
967 vector<docstring> result;
968 for (; it != end; ++it) {
969 docstring const key = *it;
970 BiblioInfo::const_iterator cit = bi.find(key);
973 if (cit->second.entryType() == entry_type)
974 result.push_back(key);
980 // Escape special chars.
981 // All characters are literals except: '.|*?+(){}[]^$\'
982 // These characters are literals when preceded by a "\", which is done here
983 // @todo: This function should be moved to support, and then the test in tests
984 // should be moved there as well.
985 static docstring escape_special_chars(docstring const & expr)
987 // Search for all chars '.|*?+(){}[^$]\'
988 // Note that '[', ']', and '\' must be escaped.
989 static const regex reg("[.|*?+(){}^$\\[\\]\\\\]");
991 // $& is an ECMAScript format expression that expands to all
992 // of the current match
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(regex_replace(to_utf8(expr), reg, string("\\$&")));
1000 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
1001 vector<docstring> const & keys_to_search, bool only_keys,
1002 docstring const & search_expression, docstring const & field,
1003 bool case_sensitive, bool re)
1005 vector<docstring> foundKeys;
1007 docstring expr = trim(search_expression);
1012 // We must escape special chars in the search_expr so that
1013 // it is treated as a simple string by regex.
1014 expr = escape_special_chars(expr);
1018 reg_exp.assign(to_utf8(expr), case_sensitive ?
1019 regex_constants::ECMAScript : regex_constants::icase);
1020 } catch (regex_error const & e) {
1021 // regex throws an exception if the regular expression is not
1023 LYXERR(Debug::GUI, e.what());
1024 return vector<docstring>();
1027 vector<docstring>::const_iterator it = keys_to_search.begin();
1028 vector<docstring>::const_iterator end = keys_to_search.end();
1029 for (; it != end; ++it ) {
1030 BiblioInfo::const_iterator info = bi.find(*it);
1031 if (info == bi.end())
1034 BibTeXInfo const & kvm = info->second;
1037 sdata = to_utf8(*it);
1038 else if (field.empty())
1039 sdata = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
1041 sdata = to_utf8(kvm[field]);
1047 if (regex_search(sdata, reg_exp))
1048 foundKeys.push_back(*it);
1050 catch (regex_error const & e) {
1051 LYXERR(Debug::GUI, e.what());
1052 return vector<docstring>();
1059 void GuiCitation::dispatchParams()
1061 std::string const lfun = InsetCommand::params2string(params_);
1062 dispatch(FuncRequest(getLfun(), lfun));
1066 BiblioInfo const & GuiCitation::bibInfo() const
1068 Buffer const & buf = documentBuffer();
1069 buf.reloadBibInfoCache();
1070 return buf.masterBibInfo();
1074 void GuiCitation::saveSession(QSettings & settings) const
1076 Dialog::saveSession(settings);
1078 sessionKey() + "/regex", regexp_->isChecked());
1080 sessionKey() + "/casesensitive", casesense_->isChecked());
1082 sessionKey() + "/autofind", instant_->isChecked());
1084 sessionKey() + "/citestyle", style_);
1086 sessionKey() + "/literal", InsetCitation::last_literal);
1090 void GuiCitation::restoreSession()
1092 Dialog::restoreSession();
1094 regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
1095 casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
1096 instant_->setChecked(settings.value(sessionKey() + "/autofind", true).toBool());
1097 style_ = settings.value(sessionKey() + "/citestyle").toString();
1098 InsetCitation::last_literal =
1099 settings.value(sessionKey() + "/literal", false).toBool();
1104 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
1107 } // namespace frontend
1110 #include "moc_GuiCitation.cpp"