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/InsetCommand.h"
32 #include "support/debug.h"
33 #include "support/docstring.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
37 #include <QCloseEvent>
41 #include <QStandardItemModel>
49 #include "support/regex.h"
56 using namespace lyx::support;
62 // I am guessing that it would not hurt to make these private members.
63 static vector<string> citeCmds_;
64 static vector<CitationStyle> citeStyles_;
67 template<typename String>
68 static QStringList to_qstring_list(vector<String> const & v)
72 for (size_t i = 0; i != v.size(); ++i) {
75 qlist.append(lyx::toqstr(v[i]));
81 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
83 vector<lyx::docstring> v;
84 for (int i = 0; i != qlist.size(); ++i) {
85 if (qlist[i].isEmpty())
87 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
93 GuiCitation::GuiCitation(GuiView & lv)
94 : DialogView(lv, "citation", qt_("Citation")),
95 style_(QString()), literal_(false), params_(insetCode("citation"))
100 filter_ = new FancyLineEdit(this);
101 filter_->setButtonPixmap(FancyLineEdit::Right, getPixmap("images/", "editclear", "svgz,png"));
102 filter_->setButtonVisible(FancyLineEdit::Right, true);
103 filter_->setButtonToolTip(FancyLineEdit::Right, qt_("Clear text"));
104 filter_->setAutoHideButton(FancyLineEdit::Right, true);
105 filter_->setPlaceholderText(qt_("All avail. citations"));
107 filterBarL->addWidget(filter_, 0);
108 findKeysLA->setBuddy(filter_);
110 // Add search options as button menu
111 regexp_ = new QAction(qt_("Regular e&xpression"), this);
112 regexp_->setCheckable(true);
113 casesense_ = new QAction(qt_("Case se&nsitive"), this);
114 casesense_->setCheckable(true);
115 instant_ = new QAction(qt_("Search as you &type"), this);
116 instant_->setCheckable(true);
117 instant_->setChecked(true);
119 QMenu * searchOpts = new QMenu(this);
120 searchOpts->addAction(regexp_);
121 searchOpts->addAction(casesense_);
122 searchOpts->addAction(instant_);
123 searchOptionsPB->setMenu(searchOpts);
125 connect(citationStyleCO, SIGNAL(activated(int)),
126 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
127 connect(starredCB, SIGNAL(clicked()),
128 this, SLOT(updateStyles()));
129 connect(literalCB, SIGNAL(clicked()),
130 this, SLOT(changed()));
131 connect(forceuppercaseCB, SIGNAL(clicked()),
132 this, SLOT(updateStyles()));
133 connect(textBeforeED, SIGNAL(textChanged(QString)),
134 this, SLOT(updateStyles()));
135 connect(textAfterED, SIGNAL(textChanged(QString)),
136 this, SLOT(updateStyles()));
137 connect(textBeforeED, SIGNAL(returnPressed()),
138 this, SLOT(on_okPB_clicked()));
139 connect(textAfterED, SIGNAL(returnPressed()),
140 this, SLOT(on_okPB_clicked()));
142 selectionManager = new GuiSelectionManager(this, availableLV, selectedLV,
143 addPB, deletePB, upPB, downPB, &available_model_, &selected_model_, 1);
144 connect(selectionManager, SIGNAL(selectionChanged()),
145 this, SLOT(setCitedKeys()));
146 connect(selectionManager, SIGNAL(updateHook()),
147 this, SLOT(updateControls()));
148 connect(selectionManager, SIGNAL(okHook()),
149 this, SLOT(on_okPB_clicked()));
151 connect(filter_, SIGNAL(rightButtonClicked()),
152 this, SLOT(resetFilter()));
153 connect(filter_, SIGNAL(textEdited(QString)),
154 this, SLOT(filterChanged(QString)));
155 connect(filter_, SIGNAL(returnPressed()),
156 this, SLOT(filterPressed()));
157 #if (QT_VERSION < 0x050000)
158 connect(filter_, SIGNAL(downPressed()),
159 availableLV, SLOT(setFocus()));
161 connect(filter_, &FancyLineEdit::downPressed,
162 availableLV, [=](){ focusAndHighlight(availableLV); });
164 connect(regexp_, SIGNAL(triggered()),
165 this, SLOT(regexChanged()));
166 connect(casesense_, SIGNAL(triggered()),
167 this, SLOT(caseChanged()));
168 connect(instant_, SIGNAL(triggered(bool)),
169 this, SLOT(instantChanged(bool)));
171 #if (QT_VERSION < 0x050000)
172 selectedLV->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
174 selectedLV->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
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)
205 availableLV->setFocus();
206 DialogView::showEvent(e);
210 void GuiCitation::on_okPB_clicked()
218 void GuiCitation::on_cancelPB_clicked()
225 void GuiCitation::on_applyPB_clicked()
231 void GuiCitation::on_restorePB_clicked()
238 void GuiCitation::on_literalCB_clicked()
240 literal_ = literalCB->isChecked();
245 void GuiCitation::updateControls()
247 BiblioInfo const & bi = bibInfo();
252 // The main point of separating this out is that the fill*() methods
253 // called in update() do not need to be called for INTERNAL updates,
254 // such as when addPB is pressed, as the list of fields, entries, etc,
255 // will not have changed.
256 void GuiCitation::updateControls(BiblioInfo const & bi)
258 QModelIndex idx = selectionManager->getSelectedIndex(1);
260 int i = citationStyleCO->currentIndex();
261 if (i == -1 || i > int(citeStyles_.size()))
263 updateFormatting(citeStyles_[i]);
264 selectionManager->update();
268 void GuiCitation::updateFormatting(CitationStyle const & currentStyle)
270 BufferParams const bp = documentBuffer().params();
271 bool const force = currentStyle.forceUpperCase;
272 bool const starred = currentStyle.hasStarredVersion;
273 bool const full = starred && bp.fullAuthorList();
274 bool const textbefore = currentStyle.textBefore;
275 bool const textafter = currentStyle.textAfter;
277 int const rows = selectedLV->model()->rowCount();
279 bool const qualified = currentStyle.hasQualifiedList
281 || !params_["pretextlist"].empty()
282 || !params_["posttextlist"].empty());
283 selectedLV->horizontalHeader()->setVisible(qualified);
284 selectedLV->setColumnHidden(0, !qualified);
285 selectedLV->setColumnHidden(2, !qualified);
286 bool const haveSelection = rows > 0;
288 textBeforeLA->setText(qt_("General text befo&re:"));
289 textAfterLA->setText(qt_("General &text after:"));
290 textBeforeED->setToolTip(qt_("Text that precedes the whole reference list. "
291 "For text that precedes individual items, "
292 "double-click on the respective entry above."));
293 textAfterLA->setToolTip(qt_("General &text after:"));
294 textAfterED->setToolTip(qt_("Text that follows the whole reference list. "
295 "For text that follows individual items, "
296 "double-click on the respective entry above."));
298 textBeforeLA->setText(qt_("Text befo&re:"));
299 if (textbefore && haveSelection)
300 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\")"));
302 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\"), "
303 "if the current citation style supports this."));
304 textAfterLA->setText(qt_("&Text after:"));
305 if (textafter && haveSelection)
306 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages)"));
308 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages), "
309 "if the current citation style supports this."));
312 forceuppercaseCB->setEnabled(force && haveSelection);
313 if (force && haveSelection)
314 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\")."));
316 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\"), "
317 "if the current citation style supports this."));
318 starredCB->setEnabled(full && haveSelection);
319 textBeforeED->setEnabled(textbefore && haveSelection);
320 textBeforeLA->setEnabled(textbefore && haveSelection);
321 textAfterED->setEnabled(textafter && haveSelection);
322 textAfterLA->setEnabled(textafter && haveSelection);
323 literalCB->setEnabled(textbefore || textafter);
324 citationStyleCO->setEnabled(haveSelection);
325 citationStyleLA->setEnabled(haveSelection);
327 // Check if we have a custom string/tooltip for the starred version
328 if (starred && !currentStyle.stardesc.empty()) {
330 bp.documentClass().getCiteMacro(bp.citeEngineType(), currentStyle.stardesc);
333 guistring = translateIfPossible(from_utf8(val));
334 starredCB->setText(toqstr(guistring));
335 starredCB->setEnabled(haveSelection);
337 if (!currentStyle.startooltip.empty()) {
338 val = bp.documentClass().getCiteMacro(bp.citeEngineType(),
339 currentStyle.startooltip);
341 guistring = translateIfPossible(from_utf8(val));
343 // Tooltip might also be empty
344 starredCB->setToolTip(toqstr(guistring));
346 // This is the default meaning of the starred commands
347 starredCB->setText(qt_("All aut&hors"));
348 if (full && haveSelection)
349 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\")"));
351 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\"), "
352 "if the current citation style supports this."));
357 // Update the styles for the style combo, citationStyleCO, and mark the
358 // settings as changed. Called upon changing the cited keys (including
359 // merely reordering the keys) or editing the text before/after fields.
360 void GuiCitation::updateStyles()
362 BiblioInfo const & bi = bibInfo();
368 // Update the styles for the style combo, citationStyleCO.
369 void GuiCitation::updateStyles(BiblioInfo const & bi)
371 QStringList selected_keys = selectedKeys();
372 int curr = selectedLV->model()->rowCount() - 1;
374 if (curr < 0 || selected_keys.empty()) {
375 citationStyleCO->clear();
376 citationStyleCO->setEnabled(false);
377 citationStyleLA->setEnabled(false);
381 static const size_t max_length = 80;
382 BiblioInfo::CiteStringMap sty = citationStyles(bi, max_length);
386 citationStyleCO->setEnabled(false);
387 citationStyleLA->setEnabled(false);
388 citationStyleCO->clear();
392 citationStyleCO->blockSignals(true);
394 // save old style selection
395 QString const curdata =
396 citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
397 QString const olddata = (curdata.isEmpty()) ? style_ : curdata;
398 citationStyleCO->clear();
399 BiblioInfo::CiteStringMap::const_iterator cit = sty.begin();
400 BiblioInfo::CiteStringMap::const_iterator end = sty.end();
401 for (int ii = 1; cit != end; ++cit, ++ii)
402 citationStyleCO->addItem(toqstr(cit->second), toqstr(cit->first));
403 citationStyleCO->setEnabled(true);
404 citationStyleLA->setEnabled(true);
405 // restore old style selection
406 int const i = citationStyleCO->findData(olddata);
408 citationStyleCO->setCurrentIndex(i);
410 citationStyleCO->blockSignals(false);
414 void GuiCitation::fillFields(BiblioInfo const & bi)
416 fieldsCO->blockSignals(true);
417 int const oldIndex = fieldsCO->currentIndex();
419 QStringList const fields = to_qstring_list(bi.getFields());
420 fieldsCO->insertItem(0, qt_("All fields"));
421 fieldsCO->insertItem(1, qt_("Keys"));
422 fieldsCO->insertItems(2, fields);
423 if (oldIndex != -1 && oldIndex < fieldsCO->count())
424 fieldsCO->setCurrentIndex(oldIndex);
425 fieldsCO->blockSignals(false);
429 void GuiCitation::fillEntries(BiblioInfo const & bi)
431 entriesCO->blockSignals(true);
432 int const oldIndex = entriesCO->currentIndex();
434 QStringList const entries = to_qstring_list(bi.getEntries());
435 entriesCO->insertItem(0, qt_("All entry types"));
436 entriesCO->insertItems(1, entries);
437 if (oldIndex != -1 && oldIndex < entriesCO->count())
438 entriesCO->setCurrentIndex(oldIndex);
439 entriesCO->blockSignals(false);
443 bool GuiCitation::isSelected(QModelIndex const & idx)
445 QString const str = idx.data().toString();
446 return selectedKeys().contains(str);
450 void GuiCitation::setButtons()
452 int const srows = selectedLV->model()->rowCount();
453 applyPB->setEnabled(srows > 0);
454 okPB->setEnabled(srows > 0);
458 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
460 if (!idx.isValid() || bi.empty()) {
461 infoML->document()->clear();
462 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
466 infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
469 QString const keytxt = toqstr(
470 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), ci));
471 infoML->document()->setHtml(keytxt);
475 void GuiCitation::findText(QString const & text, bool reset)
477 //"All Fields" and "Keys" are the first two
478 int index = fieldsCO->currentIndex() - 2;
479 BiblioInfo const & bi = bibInfo();
480 vector<docstring> const & fields = bi.getFields();
483 if (index <= -1 || index >= int(fields.size()))
484 //either "All Fields" or "Keys" or an invalid value
485 field = from_ascii("");
487 field = fields[index];
490 bool const onlyKeys = index == -1;
492 //"All Entry Types" is first.
493 index = entriesCO->currentIndex() - 1;
494 vector<docstring> const & entries = bi.getEntries();
495 docstring entry_type;
496 if (index < 0 || index >= int(entries.size()))
497 entry_type = from_ascii("");
499 entry_type = entries[index];
501 bool const case_sentitive = casesense_->isChecked();
502 bool const reg_exp = regexp_->isChecked();
504 findKey(bi, text, onlyKeys, field, entry_type,
505 case_sentitive, reg_exp, reset);
507 //It'd be nice to save and restore the current selection in
508 //availableLV. Currently, we get an automatic reset, since the
515 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
517 findText(filter_->text(), true);
521 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
523 findText(filter_->text(), true);
527 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
529 if (index >= 0 && index < citationStyleCO->count()) {
530 vector<CitationStyle> const & styles = citeStyles_;
531 updateFormatting(styles[index]);
537 void GuiCitation::filterChanged(const QString & text)
539 if (!text.isEmpty()) {
540 if (instant_->isChecked())
541 findText(filter_->text());
544 findText(filter_->text());
549 void GuiCitation::filterPressed()
551 findText(filter_->text(), true);
555 void GuiCitation::resetFilter()
557 filter_->setText(QString());
558 findText(filter_->text(), true);
562 void GuiCitation::caseChanged()
564 findText(filter_->text());
568 void GuiCitation::regexChanged()
570 findText(filter_->text());
574 void GuiCitation::updateFilterHint()
576 QString const hint = instant_->isChecked() ?
577 qt_("Enter string to filter the list of available citations") :
578 qt_("Enter string to filter the list of available citations and press <Enter>");
579 filter_->setToolTip(hint);
583 void GuiCitation::instantChanged(bool checked)
586 findText(filter_->text(), true);
592 void GuiCitation::changed()
598 void GuiCitation::applyParams(int const choice, bool full, bool force,
599 QString before, QString after)
601 if (cited_keys_.isEmpty())
604 vector<CitationStyle> const & styles = citeStyles_;
606 CitationStyle cs = styles[choice];
613 cs.forceUpperCase &= force;
614 cs.hasStarredVersion &= full;
615 string const command = citationStyleToString(cs);
617 params_.setCmdName(command);
618 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
619 params_["before"] = qstring_to_ucs4(before);
620 params_["after"] = qstring_to_ucs4(after);
621 if (cs.hasQualifiedList) {
622 params_["pretextlist"] = getStringFromVector(getPreTexts(), from_ascii("\t"));
623 params_["posttextlist"] = getStringFromVector(getPostTexts(), from_ascii("\t"));
625 params_["literal"] = literalCB->isChecked() ? from_ascii("true") : from_ascii("false");
630 void GuiCitation::clearSelection()
633 setSelectedKeys(cited_keys_);
637 void GuiCitation::setSelectedKeys(QStringList const sl)
639 selected_model_.clear();
640 selected_model_.setColumnCount(3);
642 headers << qt_("Text before")
644 << qt_("Text after");
645 selected_model_.setHorizontalHeaderLabels(headers);
646 selectedLV->setColumnHidden(0, true);
647 selectedLV->setColumnHidden(2, true);
648 selectedLV->verticalHeader()->setVisible(false);
649 selectedLV->horizontalHeader()->setVisible(false);
650 QStringList::const_iterator it = sl.begin();
651 QStringList::const_iterator end = sl.end();
652 for (int i = 0; it != end; ++it, ++i) {
653 QStandardItem * si = new QStandardItem();
657 si->setEditable(false);
658 selected_model_.setItem(i, 1, si);
663 QStringList GuiCitation::selectedKeys()
666 for (int i = 0; i != selected_model_.rowCount(); ++i) {
667 QStandardItem const * item = selected_model_.item(i, 1);
669 res.append(item->text());
675 void GuiCitation::setPreTexts(vector<docstring> const m)
677 for (docstring const & s: m) {
678 QStandardItem * si = new QStandardItem();
680 docstring pre = split(s, key, ' ');
681 si->setData(toqstr(pre));
682 si->setText(toqstr(pre));
683 QModelIndexList qmil =
684 selected_model_.match(selected_model_.index(0, 1),
685 Qt::DisplayRole, toqstr(key), 1,
686 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
688 selected_model_.setItem(qmil.front().row(), 0, si);
693 vector<docstring> GuiCitation::getPreTexts()
695 vector<docstring> res;
696 for (int i = 0; i != selected_model_.rowCount(); ++i) {
697 QStandardItem const * key = selected_model_.item(i, 1);
698 QStandardItem const * pre = selected_model_.item(i, 0);
699 if (key && pre && !key->text().isEmpty() && !pre->text().isEmpty())
700 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(pre->text()));
706 void GuiCitation::setPostTexts(vector<docstring> const m)
708 for (docstring const & s: m) {
709 QStandardItem * si = new QStandardItem();
711 docstring post = split(s, key, ' ');
712 si->setData(toqstr(post));
713 si->setText(toqstr(post));
714 QModelIndexList qmil =
715 selected_model_.match(selected_model_.index(0, 1),
716 Qt::DisplayRole, toqstr(key), 1,
717 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
719 selected_model_.setItem(qmil.front().row(), 2, si);
724 vector<docstring> GuiCitation::getPostTexts()
726 vector<docstring> res;
727 for (int i = 0; i != selected_model_.rowCount(); ++i) {
728 QStandardItem const * key = selected_model_.item(i, 1);
729 QStandardItem const * post = selected_model_.item(i, 2);
731 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(post->text()));
737 void GuiCitation::init()
739 // Make the list of all available bibliography keys
740 BiblioInfo const & bi = bibInfo();
741 all_keys_ = to_qstring_list(bi.getKeys());
743 available_model_.setStringList(all_keys_);
745 // Ditto for the keys cited in this inset
746 QString str = toqstr(params_["key"]);
750 cited_keys_ = str.split(",");
751 setSelectedKeys(cited_keys_);
753 // Initialize the drop downs
757 // Initialize the citation formatting
758 string const & cmd = params_.getCmdName();
759 CitationStyle const cs =
760 citationStyleFromString(cmd, documentBuffer().params());
762 forceuppercaseCB->setChecked(cs.forceUpperCase);
763 starredCB->setChecked(cs.hasStarredVersion &&
764 documentBuffer().params().fullAuthorList());
765 textBeforeED->setText(toqstr(params_["before"]));
766 textAfterED->setText(toqstr(params_["after"]));
768 // if this is a new citation, we set the literal checkbox
769 // to its last set value.
770 if (cited_keys_.isEmpty())
771 literalCB->setChecked(literal_);
773 literalCB->setChecked(params_["literal"] == "true");
775 setPreTexts(getVectorFromString(params_["pretextlist"], from_ascii("\t")));
776 setPostTexts(getVectorFromString(params_["posttextlist"], from_ascii("\t")));
778 // Update the interface
781 if (selected_model_.rowCount()) {
782 selectedLV->blockSignals(true);
783 selectedLV->setFocus();
784 selectedLV->selectRow(0);
785 selectedLV->blockSignals(false);
787 // Find the citation style
788 vector<string> const & cmds = citeCmds_;
789 vector<string>::const_iterator cit =
790 std::find(cmds.begin(), cmds.end(), cs.name);
792 if (cit != cmds.end())
793 i = int(cit - cmds.begin());
795 // Set the style combo appropriately
796 citationStyleCO->blockSignals(true);
797 citationStyleCO->setCurrentIndex(i);
798 citationStyleCO->blockSignals(false);
799 updateFormatting(citeStyles_[i]);
801 availableLV->setFocus();
803 applyPB->setEnabled(false);
804 okPB->setEnabled(false);
808 void GuiCitation::findKey(BiblioInfo const & bi,
809 QString const & str, bool only_keys,
810 docstring field, docstring entry_type,
811 bool case_sensitive, bool reg_exp, bool reset)
814 // This should be moved to a class member.
815 // Used for optimisation: store last searched string.
816 static QString last_searched_string;
817 // Used to disable the above optimisation.
818 static bool last_case_sensitive;
819 static bool last_reg_exp;
820 // Reset last_searched_string in case of changed option.
821 if (last_case_sensitive != case_sensitive
822 || last_reg_exp != reg_exp) {
823 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
824 last_searched_string.clear();
826 // save option for next search.
827 last_case_sensitive = case_sensitive;
828 last_reg_exp = reg_exp;
830 Qt::CaseSensitivity qtcase = case_sensitive ?
831 Qt::CaseSensitive: Qt::CaseInsensitive;
833 // If new string (str) contains the last searched one...
835 !last_searched_string.isEmpty() &&
837 str.contains(last_searched_string, qtcase))
838 // ... then only search within already found list.
839 keys = available_model_.stringList();
841 // ... else search all keys.
843 // save searched string for next search.
844 last_searched_string = str;
848 // First, filter by entry_type, which will be faster than
849 // what follows, so we may get to do that on less.
850 vector<docstring> keyVector = to_docstring_vector(keys);
851 filterByEntryType(bi, keyVector, entry_type);
854 result = to_qstring_list(keyVector);
856 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
857 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
859 available_model_.setStringList(result);
863 BiblioInfo::CiteStringMap GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
865 vector<docstring> const keys = to_docstring_vector(cited_keys_);
866 vector<CitationStyle> styles = citeStyles_;
867 int ind = citationStyleCO->currentIndex();
870 CitationStyle cs = styles[ind];
871 vector<docstring> pretexts = getPreTexts();
872 vector<docstring> posttexts = getPostTexts();
873 bool const qualified = cs.hasQualifiedList
874 && (selectedLV->model()->rowCount() > 1
876 || !posttexts.empty());
877 std::map<docstring, docstring> pres;
878 for (docstring const & s: pretexts) {
880 docstring val = split(s, key, ' ');
883 std::map<docstring, docstring> posts;
884 for (docstring const & s: posttexts) {
886 docstring val = split(s, key, ' ');
890 ci.textBefore = qstring_to_ucs4(textBeforeED->text());
891 ci.textAfter = qstring_to_ucs4(textAfterED->text());
892 ci.forceUpperCase = forceuppercaseCB->isChecked();
893 ci.Starred = starredCB->isChecked();
894 ci.context = CiteItem::Dialog;
895 ci.max_size = max_size;
896 ci.isQualified = qualified;
898 ci.posttexts = posts;
899 BiblioInfo::CiteStringMap ret = bi.getCiteStrings(keys, styles, documentBuffer(), ci);
904 void GuiCitation::setCitedKeys()
906 cited_keys_ = selectedKeys();
911 bool GuiCitation::initialiseParams(string const & data)
913 InsetCommand::string2params(data, params_);
914 citeCmds_ = documentBuffer().params().citeCommands();
915 citeStyles_ = documentBuffer().params().citeStyles();
921 void GuiCitation::clearParams()
927 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
928 vector<docstring> & keyVector, docstring entry_type)
930 if (entry_type.empty())
933 vector<docstring>::iterator it = keyVector.begin();
934 vector<docstring>::iterator end = keyVector.end();
936 vector<docstring> result;
937 for (; it != end; ++it) {
938 docstring const key = *it;
939 BiblioInfo::const_iterator cit = bi.find(key);
942 if (cit->second.entryType() == entry_type)
943 result.push_back(key);
949 // Escape special chars.
950 // All characters are literals except: '.|*?+(){}[]^$\'
951 // These characters are literals when preceded by a "\", which is done here
952 // @todo: This function should be moved to support, and then the test in tests
953 // should be moved there as well.
954 static docstring escape_special_chars(docstring const & expr)
956 // Search for all chars '.|*?+(){}[^$]\'
957 // Note that '[', ']', and '\' must be escaped.
958 static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
960 // $& is an ECMAScript format expression that expands to all
961 // of the current match
962 #ifdef LYX_USE_STD_REGEX
963 // To prefix a matched expression with a single literal backslash, we
964 // need to escape it for the C++ compiler and use:
966 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
968 // A backslash in the format string starts an escape sequence in boost.
969 // Thus, to prefix a matched expression with a single literal backslash,
970 // we need to give two backslashes to the regex engine, and escape both
971 // for the C++ compiler and use:
973 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
978 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
979 vector<docstring> const & keys_to_search, bool only_keys,
980 docstring const & search_expression, docstring field,
981 bool case_sensitive, bool regex)
983 vector<docstring> foundKeys;
985 docstring expr = trim(search_expression);
990 // We must escape special chars in the search_expr so that
991 // it is treated as a simple string by lyx::regex.
992 expr = escape_special_chars(expr);
996 reg_exp.assign(to_utf8(expr), case_sensitive ?
997 lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
998 } catch (lyx::regex_error const & e) {
999 // lyx::regex throws an exception if the regular expression is not
1001 LYXERR(Debug::GUI, e.what());
1002 return vector<docstring>();
1005 vector<docstring>::const_iterator it = keys_to_search.begin();
1006 vector<docstring>::const_iterator end = keys_to_search.end();
1007 for (; it != end; ++it ) {
1008 BiblioInfo::const_iterator info = bi.find(*it);
1009 if (info == bi.end())
1012 BibTeXInfo const & kvm = info->second;
1015 data = to_utf8(*it);
1016 else if (field.empty())
1017 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
1019 data = to_utf8(kvm[field]);
1025 if (lyx::regex_search(data, reg_exp))
1026 foundKeys.push_back(*it);
1028 catch (lyx::regex_error const & e) {
1029 LYXERR(Debug::GUI, e.what());
1030 return vector<docstring>();
1037 void GuiCitation::dispatchParams()
1039 std::string const lfun = InsetCommand::params2string(params_);
1040 dispatch(FuncRequest(getLfun(), lfun));
1044 BiblioInfo const & GuiCitation::bibInfo() const
1046 Buffer const & buf = documentBuffer();
1047 buf.reloadBibInfoCache();
1048 return buf.masterBibInfo();
1052 void GuiCitation::saveSession(QSettings & settings) const
1054 Dialog::saveSession(settings);
1056 sessionKey() + "/regex", regexp_->isChecked());
1058 sessionKey() + "/casesensitive", casesense_->isChecked());
1060 sessionKey() + "/autofind", instant_->isChecked());
1062 sessionKey() + "/citestyle", style_);
1064 sessionKey() + "/literal", literal_);
1068 void GuiCitation::restoreSession()
1070 Dialog::restoreSession();
1072 regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
1073 casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
1074 instant_->setChecked(settings.value(sessionKey() + "/autofind", true).toBool());
1075 style_ = settings.value(sessionKey() + "/citestyle").toString();
1076 literal_ = settings.value(sessionKey() + "/literal", false).toBool();
1081 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
1084 } // namespace frontend
1087 #include "moc_GuiCitation.cpp"