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 "BiblioInfo.h"
26 #include "BufferParams.h"
27 #include "TextClass.h"
28 #include "FuncRequest.h"
30 #include "insets/InsetCitation.h"
31 #include "insets/InsetCommand.h"
33 #include "support/debug.h"
34 #include "support/docstring.h"
35 #include "support/gettext.h"
36 #include "support/lstrings.h"
38 #include <QCloseEvent>
42 #include <QStandardItemModel>
50 #include "support/regex.h"
57 using namespace lyx::support;
63 // I am guessing that it would not hurt to make these private members.
64 static vector<string> citeCmds_;
65 static vector<CitationStyle> citeStyles_;
68 template<typename String>
69 static QStringList to_qstring_list(vector<String> const & v)
73 for (size_t i = 0; i != v.size(); ++i) {
76 qlist.append(lyx::toqstr(v[i]));
82 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
84 vector<lyx::docstring> v;
85 for (int i = 0; i != qlist.size(); ++i) {
86 if (qlist[i].isEmpty())
88 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
94 GuiCitation::GuiCitation(GuiView & lv)
95 : DialogView(lv, "citation", qt_("Citation")),
96 style_(QString()), params_(insetCode("citation"))
101 filter_ = new FancyLineEdit(this);
102 filter_->setButtonPixmap(FancyLineEdit::Right, getPixmap("images/", "editclear", "svgz,png"));
103 filter_->setButtonVisible(FancyLineEdit::Right, true);
104 filter_->setButtonToolTip(FancyLineEdit::Right, qt_("Clear text"));
105 filter_->setAutoHideButton(FancyLineEdit::Right, true);
106 filter_->setPlaceholderText(qt_("All avail. citations"));
108 filterBarL->addWidget(filter_, 0);
109 findKeysLA->setBuddy(filter_);
111 // Add search options as button menu
112 regexp_ = new QAction(qt_("Regular e&xpression"), this);
113 regexp_->setCheckable(true);
114 casesense_ = new QAction(qt_("Case se&nsitive"), this);
115 casesense_->setCheckable(true);
116 instant_ = new QAction(qt_("Search as you &type"), this);
117 instant_->setCheckable(true);
118 instant_->setChecked(true);
120 QMenu * searchOpts = new QMenu(this);
121 searchOpts->addAction(regexp_);
122 searchOpts->addAction(casesense_);
123 searchOpts->addAction(instant_);
124 searchOptionsPB->setMenu(searchOpts);
126 connect(citationStyleCO, SIGNAL(activated(int)),
127 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
128 connect(starredCB, SIGNAL(clicked()),
129 this, SLOT(updateStyles()));
130 connect(literalCB, SIGNAL(clicked()),
131 this, SLOT(changed()));
132 connect(forceuppercaseCB, SIGNAL(clicked()),
133 this, SLOT(updateStyles()));
134 connect(textBeforeED, SIGNAL(textChanged(QString)),
135 this, SLOT(updateStyles()));
136 connect(textAfterED, SIGNAL(textChanged(QString)),
137 this, SLOT(updateStyles()));
138 connect(textBeforeED, SIGNAL(returnPressed()),
139 this, SLOT(on_buttonBox_accepted()));
140 connect(textAfterED, SIGNAL(returnPressed()),
141 this, SLOT(on_buttonBox_accepted()));
143 selectionManager = new GuiSelectionManager(this, availableLV, selectedLV,
144 addPB, deletePB, upPB, downPB, &available_model_, &selected_model_, 1);
145 connect(selectionManager, SIGNAL(selectionChanged()),
146 this, SLOT(setCitedKeys()));
147 connect(selectionManager, SIGNAL(updateHook()),
148 this, SLOT(updateControls()));
149 connect(selectionManager, SIGNAL(okHook()),
150 this, SLOT(on_buttonBox_accepted()));
152 connect(filter_, SIGNAL(rightButtonClicked()),
153 this, SLOT(resetFilter()));
154 connect(filter_, SIGNAL(textEdited(QString)),
155 this, SLOT(filterChanged(QString)));
156 connect(filter_, SIGNAL(returnPressed()),
157 this, SLOT(filterPressed()));
158 #if (QT_VERSION < 0x050000)
159 connect(filter_, SIGNAL(downPressed()),
160 availableLV, SLOT(setFocus()));
162 connect(filter_, &FancyLineEdit::downPressed,
163 availableLV, [=](){ focusAndHighlight(availableLV); });
165 connect(regexp_, SIGNAL(triggered()),
166 this, SLOT(regexChanged()));
167 connect(casesense_, SIGNAL(triggered()),
168 this, SLOT(caseChanged()));
169 connect(instant_, SIGNAL(triggered(bool)),
170 this, SLOT(instantChanged(bool)));
172 #if (QT_VERSION < 0x050000)
173 selectedLV->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
175 selectedLV->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
178 selectedLV->setToolTip(qt_("Ordered list of all cited references.\n"
179 "You can reorder, add and remove references with the buttons on the left."));
180 setFocusProxy(filter_);
184 void GuiCitation::closeEvent(QCloseEvent * e)
187 DialogView::closeEvent(e);
191 void GuiCitation::applyView()
193 int const choice = max(0, citationStyleCO->currentIndex());
194 style_ = citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
195 bool const full = starredCB->isChecked();
196 bool const force = forceuppercaseCB->isChecked();
198 QString const before = textBeforeED->text();
199 QString const after = textAfterED->text();
201 applyParams(choice, full, force, before, after);
205 void GuiCitation::showEvent(QShowEvent * e)
207 if (!filter_->text().isEmpty())
209 availableLV->setFocus();
210 DialogView::showEvent(e);
214 void GuiCitation::on_buttonBox_accepted()
222 void GuiCitation::on_buttonBox_rejected()
229 void GuiCitation::on_buttonBox_clicked(QAbstractButton * button)
231 switch (buttonBox->standardButton(button)) {
232 case QDialogButtonBox::Apply:
235 case QDialogButtonBox::Reset:
246 void GuiCitation::on_literalCB_clicked()
248 InsetCitation::last_literal = literalCB->isChecked();
253 void GuiCitation::updateControls()
255 BiblioInfo const & bi = bibInfo();
260 // The main point of separating this out is that the fill*() methods
261 // called in update() do not need to be called for INTERNAL updates,
262 // such as when addPB is pressed, as the list of fields, entries, etc,
263 // will not have changed.
264 void GuiCitation::updateControls(BiblioInfo const & bi)
266 QModelIndex idx = selectionManager->getSelectedIndex(1);
268 int i = citationStyleCO->currentIndex();
269 if (i == -1 || i > int(citeStyles_.size()))
271 updateFormatting(citeStyles_[size_type(i)]);
272 selectionManager->update();
276 void GuiCitation::updateFormatting(CitationStyle const & currentStyle)
278 BufferParams const bp = documentBuffer().params();
279 bool const force = currentStyle.forceUpperCase;
280 bool const starred = currentStyle.hasStarredVersion;
281 bool const full = starred && bp.fullAuthorList();
282 bool const textbefore = currentStyle.textBefore;
283 bool const textafter = currentStyle.textAfter;
285 int const rows = selectedLV->model()->rowCount();
287 bool const qualified = currentStyle.hasQualifiedList && rows > 0;
289 selectedLV->horizontalHeader()->setVisible(qualified);
290 selectedLV->setColumnHidden(0, !qualified);
291 selectedLV->setColumnHidden(2, !qualified);
292 bool const haveSelection = rows > 0;
294 textBeforeLA->setText(qt_("General text befo&re:"));
295 textAfterLA->setText(qt_("General &text after:"));
296 textBeforeED->setToolTip(qt_("Text that precedes the whole reference list. "
297 "For text that precedes individual items, "
298 "double-click on the respective entry above."));
299 textAfterLA->setToolTip(qt_("General &text after:"));
300 textAfterED->setToolTip(qt_("Text that follows the whole reference list. "
301 "For text that follows individual items, "
302 "double-click on the respective entry above."));
304 textBeforeLA->setText(qt_("Text befo&re:"));
305 if (textbefore && haveSelection)
306 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\")"));
308 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\"), "
309 "if the current citation style supports this."));
310 textAfterLA->setText(qt_("&Text after:"));
311 if (textafter && haveSelection)
312 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages)"));
314 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages), "
315 "if the current citation style supports this."));
318 forceuppercaseCB->setEnabled(force && haveSelection);
319 if (force && haveSelection)
320 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\")."));
322 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\"), "
323 "if the current citation style supports this."));
324 starredCB->setEnabled(full && haveSelection);
325 textBeforeED->setEnabled(textbefore && haveSelection);
326 textBeforeLA->setEnabled(textbefore && haveSelection);
327 textAfterED->setEnabled(textafter && haveSelection);
328 textAfterLA->setEnabled(textafter && haveSelection);
329 literalCB->setEnabled(textbefore || textafter);
330 citationStyleCO->setEnabled(haveSelection);
331 citationStyleLA->setEnabled(haveSelection);
333 // Check if we have a custom string/tooltip for the starred version
334 if (starred && !currentStyle.stardesc.empty()) {
336 bp.documentClass().getCiteMacro(bp.citeEngineType(), currentStyle.stardesc);
339 guistring = translateIfPossible(from_utf8(val));
340 starredCB->setText(toqstr(guistring));
341 starredCB->setEnabled(haveSelection);
343 if (!currentStyle.startooltip.empty()) {
344 val = bp.documentClass().getCiteMacro(bp.citeEngineType(),
345 currentStyle.startooltip);
347 guistring = translateIfPossible(from_utf8(val));
349 // Tooltip might also be empty
350 starredCB->setToolTip(toqstr(guistring));
352 // This is the default meaning of the starred commands
353 starredCB->setText(qt_("All aut&hors"));
354 if (full && haveSelection)
355 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\")"));
357 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\"), "
358 "if the current citation style supports this."));
360 if (availableLV->selectionModel()->selectedIndexes().isEmpty())
361 availableLV->setToolTip(qt_("All references available for citing."));
363 availableLV->setToolTip(qt_("All references available for citing.\n"
364 "To add the selected one, hit Add, press Enter or double-click.\n"
365 "Hit Ctrl-Enter to add and close the dialog."));
366 // With qualified citation lists, it makes sense to add the same key multiple times
367 selectionManager->allowMultiSelection(currentStyle.hasQualifiedList);
371 // Update the styles for the style combo, citationStyleCO, and mark the
372 // settings as changed. Called upon changing the cited keys (including
373 // merely reordering the keys) or editing the text before/after fields.
374 void GuiCitation::updateStyles()
376 BiblioInfo const & bi = bibInfo();
382 // Update the styles for the style combo, citationStyleCO.
383 void GuiCitation::updateStyles(BiblioInfo const & bi)
385 QStringList selected_keys = selectedKeys();
386 int curr = selectedLV->model()->rowCount() - 1;
388 if (curr < 0 || selected_keys.empty()) {
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()) ? style_ : curdata;
412 citationStyleCO->clear();
413 BiblioInfo::CiteStringMap::const_iterator cit = sty.begin();
414 BiblioInfo::CiteStringMap::const_iterator end = sty.end();
415 for (int ii = 1; cit != end; ++cit, ++ii)
416 citationStyleCO->addItem(toqstr(cit->second), toqstr(cit->first));
417 citationStyleCO->setEnabled(true);
418 citationStyleLA->setEnabled(true);
419 // restore old style selection
420 int const i = citationStyleCO->findData(olddata);
422 citationStyleCO->setCurrentIndex(i);
424 citationStyleCO->blockSignals(false);
428 void GuiCitation::fillFields(BiblioInfo const & bi)
430 fieldsCO->blockSignals(true);
431 int const oldIndex = fieldsCO->currentIndex();
433 QStringList const fields = to_qstring_list(bi.getFields());
434 fieldsCO->insertItem(0, qt_("All fields"));
435 fieldsCO->insertItem(1, qt_("Keys"));
436 fieldsCO->insertItems(2, fields);
437 if (oldIndex != -1 && oldIndex < fieldsCO->count())
438 fieldsCO->setCurrentIndex(oldIndex);
439 fieldsCO->blockSignals(false);
443 void GuiCitation::fillEntries(BiblioInfo const & bi)
445 entriesCO->blockSignals(true);
446 int const oldIndex = entriesCO->currentIndex();
448 QStringList const entries = to_qstring_list(bi.getEntries());
449 entriesCO->insertItem(0, qt_("All entry types"));
450 entriesCO->insertItems(1, entries);
451 if (oldIndex != -1 && oldIndex < entriesCO->count())
452 entriesCO->setCurrentIndex(oldIndex);
453 entriesCO->blockSignals(false);
457 bool GuiCitation::isSelected(QModelIndex const & idx)
459 QString const str = idx.data().toString();
460 return selectedKeys().contains(str);
464 void GuiCitation::setButtons()
466 int const srows = selectedLV->model()->rowCount();
467 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(srows > 0);
468 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(srows > 0);
472 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
474 if (!idx.isValid() || bi.empty()) {
475 infoML->document()->clear();
476 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
480 infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
483 QString const keytxt = toqstr(
484 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), ci));
485 infoML->document()->setHtml(keytxt);
489 void GuiCitation::findText(QString const & text, bool reset)
491 //"All Fields" and "Keys" are the first two
492 int index = fieldsCO->currentIndex() - 2;
493 BiblioInfo const & bi = bibInfo();
494 vector<docstring> const & fields = bi.getFields();
497 if (index <= -1 || index >= int(fields.size()))
498 //either "All Fields" or "Keys" or an invalid value
499 field = from_ascii("");
501 field = fields[size_type(index)];
504 bool const onlyKeys = index == -1;
506 //"All Entry Types" is first.
507 index = entriesCO->currentIndex() - 1;
508 vector<docstring> const & entries = bi.getEntries();
509 docstring entry_type;
510 if (index < 0 || index >= int(entries.size()))
511 entry_type = from_ascii("");
513 entry_type = entries[size_type(index)];
515 bool const case_sentitive = casesense_->isChecked();
516 bool const reg_exp = regexp_->isChecked();
518 findKey(bi, text, onlyKeys, field, entry_type,
519 case_sentitive, reg_exp, reset);
521 //It'd be nice to save and restore the current selection in
522 //availableLV. Currently, we get an automatic reset, since the
529 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
531 findText(filter_->text(), true);
535 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
537 findText(filter_->text(), true);
541 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
543 if (index >= 0 && index < citationStyleCO->count()) {
544 vector<CitationStyle> const & styles = citeStyles_;
545 updateFormatting(styles[size_type(index)]);
551 void GuiCitation::filterChanged(const QString & text)
553 if (!text.isEmpty()) {
554 if (instant_->isChecked())
555 findText(filter_->text());
558 findText(filter_->text());
563 void GuiCitation::filterPressed()
565 findText(filter_->text(), true);
569 void GuiCitation::resetFilter()
571 filter_->setText(QString());
572 findText(filter_->text(), true);
576 void GuiCitation::caseChanged()
578 findText(filter_->text());
582 void GuiCitation::regexChanged()
584 findText(filter_->text());
588 void GuiCitation::updateFilterHint()
590 QString hint = instant_->isChecked() ?
591 qt_("Enter string to filter the list of available citations") :
592 qt_("Enter string to filter the list of available citations and press <Enter>");
593 hint += qt_("\nThe down arrow key will get you into the list of filtered citations.");
594 filter_->setToolTip(hint);
598 void GuiCitation::instantChanged(bool checked)
601 findText(filter_->text(), true);
607 void GuiCitation::changed()
613 void GuiCitation::applyParams(int const choice, bool full, bool force,
614 QString before, QString after)
616 if (cited_keys_.isEmpty())
619 vector<CitationStyle> const & styles = citeStyles_;
621 CitationStyle cs = styles[size_type(choice)];
628 cs.forceUpperCase &= force;
629 cs.hasStarredVersion &= full;
630 string const command = citationStyleToString(cs);
632 params_.setCmdName(command);
633 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
634 params_["before"] = qstring_to_ucs4(before);
635 params_["after"] = qstring_to_ucs4(after);
636 if (cs.hasQualifiedList) {
637 params_["pretextlist"] = getStringFromVector(getPreTexts(), from_ascii("\t"));
638 params_["posttextlist"] = getStringFromVector(getPostTexts(), from_ascii("\t"));
640 params_["literal"] = literalCB->isChecked() ? from_ascii("true") : from_ascii("false");
645 void GuiCitation::clearSelection()
648 setSelectedKeys(cited_keys_);
652 void GuiCitation::setSelectedKeys(QStringList const sl)
654 selected_model_.clear();
655 selected_model_.setColumnCount(3);
657 headers << qt_("Text before")
659 << qt_("Text after");
660 selected_model_.setHorizontalHeaderLabels(headers);
661 selectedLV->setColumnHidden(0, true);
662 selectedLV->setColumnHidden(2, true);
663 selectedLV->verticalHeader()->setVisible(false);
664 selectedLV->horizontalHeader()->setVisible(false);
665 QStringList::const_iterator it = sl.begin();
666 QStringList::const_iterator end = sl.end();
667 for (int i = 0; it != end; ++it, ++i) {
668 QStandardItem * si = new QStandardItem();
672 si->setEditable(false);
673 selected_model_.setItem(i, 1, si);
678 QStringList GuiCitation::selectedKeys()
681 for (int i = 0; i != selected_model_.rowCount(); ++i) {
682 QStandardItem const * item = selected_model_.item(i, 1);
684 res.append(item->text());
690 void GuiCitation::setPreTexts(vector<docstring> const & m)
692 // account for multiple use of the same keys
693 QList<QModelIndex> handled;
694 for (docstring const & s: m) {
695 QStandardItem * si = new QStandardItem();
697 docstring pre = split(s, key, ' ');
698 si->setData(toqstr(pre));
699 si->setText(toqstr(pre));
700 QModelIndexList qmil =
701 selected_model_.match(selected_model_.index(0, 1),
702 Qt::DisplayRole, toqstr(key), -1,
703 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
704 for (int i = 0; i < qmil.size(); ++i){
705 QModelIndex idx = qmil[i];
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 (int i = 0; i < qmil.size(); ++i){
744 QModelIndex idx = qmil[i];
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 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 lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
991 // $& is an ECMAScript format expression that expands to all
992 // of the current match
993 #ifdef LYX_USE_STD_REGEX
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("\\$&")));
999 // A backslash in the format string starts an escape sequence in boost.
1000 // Thus, to prefix a matched expression with a single literal backslash,
1001 // we need to give two backslashes to the regex engine, and escape both
1002 // for the C++ compiler and use:
1004 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
1009 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
1010 vector<docstring> const & keys_to_search, bool only_keys,
1011 docstring const & search_expression, docstring field,
1012 bool case_sensitive, bool regex)
1014 vector<docstring> foundKeys;
1016 docstring expr = trim(search_expression);
1021 // We must escape special chars in the search_expr so that
1022 // it is treated as a simple string by lyx::regex.
1023 expr = escape_special_chars(expr);
1027 reg_exp.assign(to_utf8(expr), case_sensitive ?
1028 lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
1029 } catch (lyx::regex_error const & e) {
1030 // lyx::regex throws an exception if the regular expression is not
1032 LYXERR(Debug::GUI, e.what());
1033 return vector<docstring>();
1036 vector<docstring>::const_iterator it = keys_to_search.begin();
1037 vector<docstring>::const_iterator end = keys_to_search.end();
1038 for (; it != end; ++it ) {
1039 BiblioInfo::const_iterator info = bi.find(*it);
1040 if (info == bi.end())
1043 BibTeXInfo const & kvm = info->second;
1046 sdata = to_utf8(*it);
1047 else if (field.empty())
1048 sdata = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
1050 sdata = to_utf8(kvm[field]);
1056 if (lyx::regex_search(sdata, reg_exp))
1057 foundKeys.push_back(*it);
1059 catch (lyx::regex_error const & e) {
1060 LYXERR(Debug::GUI, e.what());
1061 return vector<docstring>();
1068 void GuiCitation::dispatchParams()
1070 std::string const lfun = InsetCommand::params2string(params_);
1071 dispatch(FuncRequest(getLfun(), lfun));
1075 BiblioInfo const & GuiCitation::bibInfo() const
1077 Buffer const & buf = documentBuffer();
1078 buf.reloadBibInfoCache();
1079 return buf.masterBibInfo();
1083 void GuiCitation::saveSession(QSettings & settings) const
1085 Dialog::saveSession(settings);
1087 sessionKey() + "/regex", regexp_->isChecked());
1089 sessionKey() + "/casesensitive", casesense_->isChecked());
1091 sessionKey() + "/autofind", instant_->isChecked());
1093 sessionKey() + "/citestyle", style_);
1095 sessionKey() + "/literal", InsetCitation::last_literal);
1099 void GuiCitation::restoreSession()
1101 Dialog::restoreSession();
1103 regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
1104 casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
1105 instant_->setChecked(settings.value(sessionKey() + "/autofind", true).toBool());
1106 style_ = settings.value(sessionKey() + "/citestyle").toString();
1107 InsetCitation::last_literal =
1108 settings.value(sessionKey() + "/literal", false).toBool();
1113 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
1116 } // namespace frontend
1119 #include "moc_GuiCitation.cpp"