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
289 || !params_["pretextlist"].empty()
290 || !params_["posttextlist"].empty()
291 || !getPreTexts().empty()
292 || !getPostTexts().empty());
294 selectedLV->horizontalHeader()->setVisible(qualified);
295 selectedLV->setColumnHidden(0, !qualified);
296 selectedLV->setColumnHidden(2, !qualified);
297 bool const haveSelection = rows > 0;
299 textBeforeLA->setText(qt_("General text befo&re:"));
300 textAfterLA->setText(qt_("General &text after:"));
301 textBeforeED->setToolTip(qt_("Text that precedes the whole reference list. "
302 "For text that precedes individual items, "
303 "double-click on the respective entry above."));
304 textAfterLA->setToolTip(qt_("General &text after:"));
305 textAfterED->setToolTip(qt_("Text that follows the whole reference list. "
306 "For text that follows individual items, "
307 "double-click on the respective entry above."));
309 textBeforeLA->setText(qt_("Text befo&re:"));
310 if (textbefore && haveSelection)
311 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\")"));
313 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\"), "
314 "if the current citation style supports this."));
315 textAfterLA->setText(qt_("&Text after:"));
316 if (textafter && haveSelection)
317 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages)"));
319 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages), "
320 "if the current citation style supports this."));
323 forceuppercaseCB->setEnabled(force && haveSelection);
324 if (force && haveSelection)
325 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\")."));
327 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\"), "
328 "if the current citation style supports this."));
329 starredCB->setEnabled(full && haveSelection);
330 textBeforeED->setEnabled(textbefore && haveSelection);
331 textBeforeLA->setEnabled(textbefore && haveSelection);
332 textAfterED->setEnabled(textafter && haveSelection);
333 textAfterLA->setEnabled(textafter && haveSelection);
334 literalCB->setEnabled(textbefore || textafter);
335 citationStyleCO->setEnabled(haveSelection);
336 citationStyleLA->setEnabled(haveSelection);
338 // Check if we have a custom string/tooltip for the starred version
339 if (starred && !currentStyle.stardesc.empty()) {
341 bp.documentClass().getCiteMacro(bp.citeEngineType(), currentStyle.stardesc);
344 guistring = translateIfPossible(from_utf8(val));
345 starredCB->setText(toqstr(guistring));
346 starredCB->setEnabled(haveSelection);
348 if (!currentStyle.startooltip.empty()) {
349 val = bp.documentClass().getCiteMacro(bp.citeEngineType(),
350 currentStyle.startooltip);
352 guistring = translateIfPossible(from_utf8(val));
354 // Tooltip might also be empty
355 starredCB->setToolTip(toqstr(guistring));
357 // This is the default meaning of the starred commands
358 starredCB->setText(qt_("All aut&hors"));
359 if (full && haveSelection)
360 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\")"));
362 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\"), "
363 "if the current citation style supports this."));
365 if (availableLV->selectionModel()->selectedIndexes().isEmpty())
366 availableLV->setToolTip(qt_("All references available for citing."));
368 availableLV->setToolTip(qt_("All references available for citing.\n"
369 "To add the selected one, hit Add, press Enter or double-click.\n"
370 "Hit Ctrl-Enter to add and close the dialog."));
374 // Update the styles for the style combo, citationStyleCO, and mark the
375 // settings as changed. Called upon changing the cited keys (including
376 // merely reordering the keys) or editing the text before/after fields.
377 void GuiCitation::updateStyles()
379 BiblioInfo const & bi = bibInfo();
385 // Update the styles for the style combo, citationStyleCO.
386 void GuiCitation::updateStyles(BiblioInfo const & bi)
388 QStringList selected_keys = selectedKeys();
389 int curr = selectedLV->model()->rowCount() - 1;
391 if (curr < 0 || selected_keys.empty()) {
392 citationStyleCO->clear();
393 citationStyleCO->setEnabled(false);
394 citationStyleLA->setEnabled(false);
398 static const size_t max_length = 80;
399 BiblioInfo::CiteStringMap sty = citationStyles(bi, max_length);
403 citationStyleCO->setEnabled(false);
404 citationStyleLA->setEnabled(false);
405 citationStyleCO->clear();
409 citationStyleCO->blockSignals(true);
411 // save old style selection
412 QString const curdata =
413 citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
414 QString const olddata = (curdata.isEmpty()) ? style_ : curdata;
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 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));
706 selected_model_.setItem(qmil.front().row(), 0, si);
711 vector<docstring> GuiCitation::getPreTexts()
713 vector<docstring> res;
714 for (int i = 0; i != selected_model_.rowCount(); ++i) {
715 QStandardItem const * key = selected_model_.item(i, 1);
716 QStandardItem const * pre = selected_model_.item(i, 0);
717 if (key && pre && !key->text().isEmpty() && !pre->text().isEmpty())
718 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(pre->text()));
724 void GuiCitation::setPostTexts(vector<docstring> const m)
726 for (docstring const & s: m) {
727 QStandardItem * si = new QStandardItem();
729 docstring post = split(s, key, ' ');
730 si->setData(toqstr(post));
731 si->setText(toqstr(post));
732 QModelIndexList qmil =
733 selected_model_.match(selected_model_.index(0, 1),
734 Qt::DisplayRole, toqstr(key), 1,
735 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
737 selected_model_.setItem(qmil.front().row(), 2, si);
742 vector<docstring> GuiCitation::getPostTexts()
744 vector<docstring> res;
745 for (int i = 0; i != selected_model_.rowCount(); ++i) {
746 QStandardItem const * key = selected_model_.item(i, 1);
747 QStandardItem const * post = selected_model_.item(i, 2);
748 if (key && post && !key->text().isEmpty() && !post->text().isEmpty())
749 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(post->text()));
755 void GuiCitation::init()
757 // Make the list of all available bibliography keys
758 BiblioInfo const & bi = bibInfo();
759 all_keys_ = to_qstring_list(bi.getKeys());
761 available_model_.setStringList(all_keys_);
763 // Ditto for the keys cited in this inset
764 QString str = toqstr(params_["key"]);
768 cited_keys_ = str.split(",");
769 setSelectedKeys(cited_keys_);
771 // Initialize the drop downs
775 // Initialize the citation formatting
776 string const & cmd = params_.getCmdName();
777 CitationStyle const cs =
778 citationStyleFromString(cmd, documentBuffer().params());
780 forceuppercaseCB->setChecked(cs.forceUpperCase);
781 starredCB->setChecked(cs.hasStarredVersion &&
782 documentBuffer().params().fullAuthorList());
783 textBeforeED->setText(toqstr(params_["before"]));
784 textAfterED->setText(toqstr(params_["after"]));
786 // if this is a new citation, we set the literal checkbox
787 // to its last set value.
788 if (cited_keys_.isEmpty())
789 literalCB->setChecked(InsetCitation::last_literal);
791 literalCB->setChecked(params_["literal"] == "true");
793 setPreTexts(getVectorFromString(params_["pretextlist"], from_ascii("\t")));
794 setPostTexts(getVectorFromString(params_["posttextlist"], from_ascii("\t")));
796 // Update the interface
799 if (selected_model_.rowCount()) {
800 selectedLV->blockSignals(true);
801 selectedLV->setFocus();
802 selectedLV->selectRow(0);
803 selectedLV->blockSignals(false);
805 // Find the citation style
806 vector<string> const & cmds = citeCmds_;
807 vector<string>::const_iterator cit =
808 std::find(cmds.begin(), cmds.end(), cs.name);
810 if (cit != cmds.end())
811 i = int(cit - cmds.begin());
813 // Set the style combo appropriately
814 citationStyleCO->blockSignals(true);
815 citationStyleCO->setCurrentIndex(i);
816 citationStyleCO->blockSignals(false);
817 updateFormatting(citeStyles_[size_type(i)]);
819 availableLV->setFocus();
821 buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
822 buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
826 void GuiCitation::findKey(BiblioInfo const & bi,
827 QString const & str, bool only_keys,
828 docstring field, docstring entry_type,
829 bool case_sensitive, bool reg_exp, bool reset)
832 // This should be moved to a class member.
833 // Used for optimisation: store last searched string.
834 static QString last_searched_string;
835 // Used to disable the above optimisation.
836 static bool last_case_sensitive;
837 static bool last_reg_exp;
838 // Reset last_searched_string in case of changed option.
839 if (last_case_sensitive != case_sensitive
840 || last_reg_exp != reg_exp) {
841 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
842 last_searched_string.clear();
844 // save option for next search.
845 last_case_sensitive = case_sensitive;
846 last_reg_exp = reg_exp;
848 Qt::CaseSensitivity qtcase = case_sensitive ?
849 Qt::CaseSensitive: Qt::CaseInsensitive;
851 // If new string (str) contains the last searched one...
853 !last_searched_string.isEmpty() &&
855 str.contains(last_searched_string, qtcase))
856 // ... then only search within already found list.
857 keys = available_model_.stringList();
859 // ... else search all keys.
861 // save searched string for next search.
862 last_searched_string = str;
866 // First, filter by entry_type, which will be faster than
867 // what follows, so we may get to do that on less.
868 vector<docstring> keyVector = to_docstring_vector(keys);
869 filterByEntryType(bi, keyVector, entry_type);
872 result = to_qstring_list(keyVector);
874 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
875 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
877 available_model_.setStringList(result);
881 BiblioInfo::CiteStringMap GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
883 vector<docstring> const keys = to_docstring_vector(cited_keys_);
884 vector<CitationStyle> styles = citeStyles_;
885 int ind = citationStyleCO->currentIndex();
888 CitationStyle cs = styles[size_type(ind)];
889 vector<docstring> pretexts = getPreTexts();
890 vector<docstring> posttexts = getPostTexts();
891 bool const qualified = cs.hasQualifiedList
892 && (selectedLV->model()->rowCount() > 1
894 || !posttexts.empty());
895 std::map<docstring, docstring> pres;
896 for (docstring const & s: pretexts) {
898 docstring val = split(s, key, ' ');
901 std::map<docstring, docstring> posts;
902 for (docstring const & s: posttexts) {
904 docstring val = split(s, key, ' ');
908 ci.textBefore = qstring_to_ucs4(textBeforeED->text());
909 ci.textAfter = qstring_to_ucs4(textAfterED->text());
910 ci.forceUpperCase = forceuppercaseCB->isChecked();
911 ci.Starred = starredCB->isChecked();
912 ci.context = CiteItem::Dialog;
913 ci.max_size = max_size;
914 ci.isQualified = qualified;
916 ci.posttexts = posts;
917 BiblioInfo::CiteStringMap ret = bi.getCiteStrings(keys, styles, documentBuffer(), ci);
922 void GuiCitation::setCitedKeys()
924 cited_keys_ = selectedKeys();
929 bool GuiCitation::initialiseParams(string const & sdata)
931 InsetCommand::string2params(sdata, params_);
932 citeCmds_ = documentBuffer().params().citeCommands();
933 citeStyles_ = documentBuffer().params().citeStyles();
939 void GuiCitation::clearParams()
945 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
946 vector<docstring> & keyVector, docstring entry_type)
948 if (entry_type.empty())
951 vector<docstring>::iterator it = keyVector.begin();
952 vector<docstring>::iterator end = keyVector.end();
954 vector<docstring> result;
955 for (; it != end; ++it) {
956 docstring const key = *it;
957 BiblioInfo::const_iterator cit = bi.find(key);
960 if (cit->second.entryType() == entry_type)
961 result.push_back(key);
967 // Escape special chars.
968 // All characters are literals except: '.|*?+(){}[]^$\'
969 // These characters are literals when preceded by a "\", which is done here
970 // @todo: This function should be moved to support, and then the test in tests
971 // should be moved there as well.
972 static docstring escape_special_chars(docstring const & expr)
974 // Search for all chars '.|*?+(){}[^$]\'
975 // Note that '[', ']', and '\' must be escaped.
976 static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
978 // $& is an ECMAScript format expression that expands to all
979 // of the current match
980 #ifdef LYX_USE_STD_REGEX
981 // To prefix a matched expression with a single literal backslash, we
982 // need to escape it for the C++ compiler and use:
984 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
986 // A backslash in the format string starts an escape sequence in boost.
987 // Thus, to prefix a matched expression with a single literal backslash,
988 // we need to give two backslashes to the regex engine, and escape both
989 // for the C++ compiler and use:
991 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
996 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
997 vector<docstring> const & keys_to_search, bool only_keys,
998 docstring const & search_expression, docstring field,
999 bool case_sensitive, bool regex)
1001 vector<docstring> foundKeys;
1003 docstring expr = trim(search_expression);
1008 // We must escape special chars in the search_expr so that
1009 // it is treated as a simple string by lyx::regex.
1010 expr = escape_special_chars(expr);
1014 reg_exp.assign(to_utf8(expr), case_sensitive ?
1015 lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
1016 } catch (lyx::regex_error const & e) {
1017 // lyx::regex throws an exception if the regular expression is not
1019 LYXERR(Debug::GUI, e.what());
1020 return vector<docstring>();
1023 vector<docstring>::const_iterator it = keys_to_search.begin();
1024 vector<docstring>::const_iterator end = keys_to_search.end();
1025 for (; it != end; ++it ) {
1026 BiblioInfo::const_iterator info = bi.find(*it);
1027 if (info == bi.end())
1030 BibTeXInfo const & kvm = info->second;
1033 sdata = to_utf8(*it);
1034 else if (field.empty())
1035 sdata = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
1037 sdata = to_utf8(kvm[field]);
1043 if (lyx::regex_search(sdata, reg_exp))
1044 foundKeys.push_back(*it);
1046 catch (lyx::regex_error const & e) {
1047 LYXERR(Debug::GUI, e.what());
1048 return vector<docstring>();
1055 void GuiCitation::dispatchParams()
1057 std::string const lfun = InsetCommand::params2string(params_);
1058 dispatch(FuncRequest(getLfun(), lfun));
1062 BiblioInfo const & GuiCitation::bibInfo() const
1064 Buffer const & buf = documentBuffer();
1065 buf.reloadBibInfoCache();
1066 return buf.masterBibInfo();
1070 void GuiCitation::saveSession(QSettings & settings) const
1072 Dialog::saveSession(settings);
1074 sessionKey() + "/regex", regexp_->isChecked());
1076 sessionKey() + "/casesensitive", casesense_->isChecked());
1078 sessionKey() + "/autofind", instant_->isChecked());
1080 sessionKey() + "/citestyle", style_);
1082 sessionKey() + "/literal", InsetCitation::last_literal);
1086 void GuiCitation::restoreSession()
1088 Dialog::restoreSession();
1090 regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
1091 casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
1092 instant_->setChecked(settings.value(sessionKey() + "/autofind", true).toBool());
1093 style_ = settings.value(sessionKey() + "/citestyle").toString();
1094 InsetCitation::last_literal =
1095 settings.value(sessionKey() + "/literal", false).toBool();
1100 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
1103 } // namespace frontend
1106 #include "moc_GuiCitation.cpp"