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 "LyXToolBox.h"
22 #include "qt_helpers.h"
25 #include "BufferView.h"
26 #include "BiblioInfo.h"
27 #include "BufferParams.h"
28 #include "TextClass.h"
29 #include "FuncRequest.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_(0), 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(forceuppercaseCB, SIGNAL(clicked()),
131 this, SLOT(updateStyles()));
132 connect(textBeforeED, SIGNAL(textChanged(QString)),
133 this, SLOT(updateStyles()));
134 connect(textAfterED, SIGNAL(textChanged(QString)),
135 this, SLOT(updateStyles()));
136 connect(textBeforeED, SIGNAL(returnPressed()),
137 this, SLOT(on_okPB_clicked()));
138 connect(textAfterED, SIGNAL(returnPressed()),
139 this, SLOT(on_okPB_clicked()));
141 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
142 addPB, deletePB, upPB, downPB, &available_model_, &selected_model_, 1);
143 connect(selectionManager, SIGNAL(selectionChanged()),
144 this, SLOT(setCitedKeys()));
145 connect(selectionManager, SIGNAL(updateHook()),
146 this, SLOT(updateControls()));
147 connect(selectionManager, SIGNAL(okHook()),
148 this, SLOT(on_okPB_clicked()));
150 connect(filter_, SIGNAL(rightButtonClicked()),
151 this, SLOT(resetFilter()));
152 connect(filter_, SIGNAL(textEdited(QString)),
153 this, SLOT(filterChanged(QString)));
154 connect(filter_, SIGNAL(returnPressed()),
155 this, SLOT(filterPressed()));
156 connect(regexp_, SIGNAL(triggered()),
157 this, SLOT(regexChanged()));
158 connect(casesense_, SIGNAL(triggered()),
159 this, SLOT(caseChanged()));
160 connect(instant_, SIGNAL(triggered(bool)),
161 this, SLOT(instantChanged(bool)));
163 #if (QT_VERSION < 0x050000)
164 selectedLV->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
166 selectedLV->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
169 setFocusProxy(filter_);
173 GuiCitation::~GuiCitation()
175 delete selectionManager;
179 void GuiCitation::closeEvent(QCloseEvent * e)
182 DialogView::closeEvent(e);
186 void GuiCitation::applyView()
188 int const choice = max(0, citationStyleCO->currentIndex());
190 bool const full = starredCB->isChecked();
191 bool const force = forceuppercaseCB->isChecked();
193 QString const before = textBeforeED->text();
194 QString const after = textAfterED->text();
196 applyParams(choice, full, force, before, after);
200 void GuiCitation::showEvent(QShowEvent * e)
203 availableLV->setFocus();
204 DialogView::showEvent(e);
208 void GuiCitation::on_okPB_clicked()
216 void GuiCitation::on_cancelPB_clicked()
223 void GuiCitation::on_applyPB_clicked()
229 void GuiCitation::on_restorePB_clicked()
236 void GuiCitation::updateControls()
238 BiblioInfo const & bi = bibInfo();
243 // The main point of separating this out is that the fill*() methods
244 // called in update() do not need to be called for INTERNAL updates,
245 // such as when addPB is pressed, as the list of fields, entries, etc,
246 // will not have changed.
247 void GuiCitation::updateControls(BiblioInfo const & bi)
249 QModelIndex idx = selectionManager->getSelectedIndex(1);
251 selectionManager->update();
255 void GuiCitation::updateFormatting(CitationStyle currentStyle)
257 BufferParams const bp = documentBuffer().params();
258 bool const force = currentStyle.forceUpperCase;
259 bool const starred = currentStyle.hasStarredVersion;
260 bool const full = starred && bp.fullAuthorList();
261 bool const textbefore = currentStyle.textBefore;
262 bool const textafter = currentStyle.textAfter;
264 int const rows = selectedLV->model()->rowCount();
266 bool const qualified = currentStyle.hasQualifiedList
268 || !params_["pretextlist"].empty()
269 || !params_["posttextlist"].empty());
270 selectedLV->horizontalHeader()->setVisible(qualified);
271 selectedLV->setColumnHidden(0, !qualified);
272 selectedLV->setColumnHidden(2, !qualified);
274 textBeforeLA->setText(qt_("General text befo&re:"));
275 textAfterLA->setText(qt_("General &text after:"));
276 textBeforeED->setToolTip(qt_("Text that precedes the whole reference list. "
277 "For text that precedes individual items, double-click on the respective entry above."));
278 textAfterLA->setToolTip(qt_("General &text after:"));
279 textAfterED->setToolTip(qt_("Text that follows the whole reference list. "
280 "For text that follows individual items, double-click on the respective entry above."));
282 textBeforeLA->setText(qt_("Text befo&re:"));
283 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\")"));
284 textAfterLA->setText(qt_("&Text after:"));
285 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages)"));
288 bool const haveSelection = rows > 0;
290 forceuppercaseCB->setEnabled(force && haveSelection);
291 starredCB->setEnabled(full && haveSelection);
292 textBeforeED->setEnabled(textbefore && haveSelection);
293 textBeforeLA->setEnabled(textbefore && haveSelection);
294 textAfterED->setEnabled(textafter && haveSelection);
295 textAfterLA->setEnabled(textafter && haveSelection);
296 citationStyleCO->setEnabled(haveSelection);
297 citationStyleLA->setEnabled(haveSelection);
299 // Check if we have a custom string/tooltip for the starred version
300 if (starred && !currentStyle.stardesc.empty()) {
302 bp.documentClass().getCiteMacro(bp.citeEngineType(), currentStyle.stardesc);
305 guistring = translateIfPossible(from_utf8(val));
306 starredCB->setText(toqstr(guistring));
307 starredCB->setEnabled(haveSelection);
309 if (!currentStyle.startooltip.empty()) {
310 val = bp.documentClass().getCiteMacro(bp.citeEngineType(),
311 currentStyle.startooltip);
313 guistring = translateIfPossible(from_utf8(val));
315 // Tooltip might also be empty
316 starredCB->setToolTip(toqstr(guistring));
318 // This is the default meaning of the starred commands
319 starredCB->setText(qt_("All aut&hors"));
320 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\")"));
325 // Update the styles for the style combo, citationStyleCO, and mark the
326 // settings as changed. Called upon changing the cited keys (including
327 // merely reordering the keys) or editing the text before/after fields.
328 void GuiCitation::updateStyles()
330 BiblioInfo const & bi = bibInfo();
336 // Update the styles for the style combo, citationStyleCO.
337 void GuiCitation::updateStyles(BiblioInfo const & bi)
339 QStringList selected_keys = selectedKeys();
340 int curr = selectedLV->model()->rowCount() - 1;
342 if (curr < 0 || selected_keys.empty()) {
343 citationStyleCO->clear();
344 citationStyleCO->setEnabled(false);
345 citationStyleLA->setEnabled(false);
349 static const size_t max_length = 80;
350 QStringList sty = citationStyles(bi, max_length);
354 citationStyleCO->setEnabled(false);
355 citationStyleLA->setEnabled(false);
356 citationStyleCO->clear();
360 citationStyleCO->blockSignals(true);
363 int const curindex = citationStyleCO->currentIndex();
364 int const oldIndex = (curindex < 0) ? style_ : curindex;
365 citationStyleCO->clear();
366 citationStyleCO->insertItems(0, sty);
367 citationStyleCO->setEnabled(true);
368 citationStyleLA->setEnabled(true);
370 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
371 citationStyleCO->setCurrentIndex(oldIndex);
373 citationStyleCO->blockSignals(false);
377 void GuiCitation::fillFields(BiblioInfo const & bi)
379 fieldsCO->blockSignals(true);
380 int const oldIndex = fieldsCO->currentIndex();
382 QStringList const fields = to_qstring_list(bi.getFields());
383 fieldsCO->insertItem(0, qt_("All fields"));
384 fieldsCO->insertItem(1, qt_("Keys"));
385 fieldsCO->insertItems(2, fields);
386 if (oldIndex != -1 && oldIndex < fieldsCO->count())
387 fieldsCO->setCurrentIndex(oldIndex);
388 fieldsCO->blockSignals(false);
392 void GuiCitation::fillEntries(BiblioInfo const & bi)
394 entriesCO->blockSignals(true);
395 int const oldIndex = entriesCO->currentIndex();
397 QStringList const entries = to_qstring_list(bi.getEntries());
398 entriesCO->insertItem(0, qt_("All entry types"));
399 entriesCO->insertItems(1, entries);
400 if (oldIndex != -1 && oldIndex < entriesCO->count())
401 entriesCO->setCurrentIndex(oldIndex);
402 entriesCO->blockSignals(false);
406 bool GuiCitation::isSelected(QModelIndex const & idx)
408 QString const str = idx.data().toString();
409 return selectedKeys().contains(str);
413 void GuiCitation::setButtons()
415 int const srows = selectedLV->model()->rowCount();
416 applyPB->setEnabled(srows > 0);
417 okPB->setEnabled(srows > 0);
421 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
423 if (!idx.isValid() || bi.empty()) {
424 infoML->document()->clear();
425 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
429 infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
432 QString const keytxt = toqstr(
433 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), ci));
434 infoML->document()->setHtml(keytxt);
438 void GuiCitation::findText(QString const & text, bool reset)
440 //"All Fields" and "Keys" are the first two
441 int index = fieldsCO->currentIndex() - 2;
442 BiblioInfo const & bi = bibInfo();
443 vector<docstring> const & fields = bi.getFields();
446 if (index <= -1 || index >= int(fields.size()))
447 //either "All Fields" or "Keys" or an invalid value
448 field = from_ascii("");
450 field = fields[index];
453 bool const onlyKeys = index == -1;
455 //"All Entry Types" is first.
456 index = entriesCO->currentIndex() - 1;
457 vector<docstring> const & entries = bi.getEntries();
458 docstring entry_type;
459 if (index < 0 || index >= int(entries.size()))
460 entry_type = from_ascii("");
462 entry_type = entries[index];
464 bool const case_sentitive = casesense_->isChecked();
465 bool const reg_exp = regexp_->isChecked();
467 findKey(bi, text, onlyKeys, field, entry_type,
468 case_sentitive, reg_exp, reset);
470 //It'd be nice to save and restore the current selection in
471 //availableLV. Currently, we get an automatic reset, since the
478 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
480 findText(filter_->text(), true);
484 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
486 findText(filter_->text(), true);
490 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
492 if (index >= 0 && index < citationStyleCO->count()) {
493 vector<CitationStyle> const & styles = citeStyles_;
494 updateFormatting(styles[index]);
500 void GuiCitation::filterChanged(const QString & text)
502 if (!text.isEmpty()) {
503 if (instant_->isChecked())
504 findText(filter_->text());
507 findText(filter_->text());
512 void GuiCitation::filterPressed()
514 findText(filter_->text(), true);
518 void GuiCitation::resetFilter()
520 filter_->setText(QString());
521 findText(filter_->text(), true);
525 void GuiCitation::caseChanged()
527 findText(filter_->text());
531 void GuiCitation::regexChanged()
533 findText(filter_->text());
537 void GuiCitation::updateFilterHint()
539 QString const hint = instant_->isChecked() ?
540 qt_("Enter string to filter the list of available citations") :
541 qt_("Enter string to filter the list of available citations and press <Enter>");
542 filter_->setToolTip(hint);
546 void GuiCitation::instantChanged(bool checked)
549 findText(filter_->text(), true);
555 void GuiCitation::changed()
561 void GuiCitation::applyParams(int const choice, bool full, bool force,
562 QString before, QString after)
564 if (cited_keys_.isEmpty())
567 vector<CitationStyle> const & styles = citeStyles_;
569 CitationStyle cs = styles[choice];
576 cs.forceUpperCase &= force;
577 cs.hasStarredVersion &= full;
578 string const command = citationStyleToString(cs);
580 params_.setCmdName(command);
581 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
582 params_["before"] = qstring_to_ucs4(before);
583 params_["after"] = qstring_to_ucs4(after);
584 if (cs.hasQualifiedList) {
585 params_["pretextlist"] = getStringFromVector(getPreTexts(), from_ascii("\t"));
586 params_["posttextlist"] = getStringFromVector(getPostTexts(), from_ascii("\t"));
592 void GuiCitation::clearSelection()
595 setSelectedKeys(cited_keys_);
599 void GuiCitation::setSelectedKeys(QStringList const sl)
601 selected_model_.clear();
602 selected_model_.setColumnCount(3);
604 headers << qt_("Text before")
606 << qt_("Text after");
607 selected_model_.setHorizontalHeaderLabels(headers);
608 selectedLV->setColumnHidden(0, true);
609 selectedLV->setColumnHidden(2, true);
610 selectedLV->verticalHeader()->setVisible(false);
611 selectedLV->horizontalHeader()->setVisible(false);
612 QStringList::const_iterator it = sl.begin();
613 QStringList::const_iterator end = sl.end();
614 for (int i = 0; it != end; ++it, ++i) {
615 QStandardItem * si = new QStandardItem();
619 si->setEditable(false);
620 selected_model_.setItem(i, 1, si);
625 QStringList GuiCitation::selectedKeys()
628 for (int i = 0; i != selected_model_.rowCount(); ++i) {
629 QStandardItem const * item = selected_model_.item(i, 1);
631 res.append(item->text());
637 void GuiCitation::setPreTexts(vector<docstring> const m)
639 for (docstring const & s: m) {
640 QStandardItem * si = new QStandardItem();
642 docstring pre = split(s, key, ' ');
643 si->setData(toqstr(pre));
644 si->setText(toqstr(pre));
645 QModelIndexList qmil =
646 selected_model_.match(selected_model_.index(0, 1),
647 Qt::DisplayRole, toqstr(key), 1,
648 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
650 selected_model_.setItem(qmil.front().row(), 0, si);
655 vector<docstring> GuiCitation::getPreTexts()
657 vector<docstring> res;
658 for (int i = 0; i != selected_model_.rowCount(); ++i) {
659 QStandardItem const * key = selected_model_.item(i, 1);
660 QStandardItem const * pre = selected_model_.item(i, 0);
661 if (key && pre && !key->text().isEmpty() && !pre->text().isEmpty())
662 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(pre->text()));
668 void GuiCitation::setPostTexts(vector<docstring> const m)
670 for (docstring const & s: m) {
671 QStandardItem * si = new QStandardItem();
673 docstring post = split(s, key, ' ');
674 si->setData(toqstr(post));
675 si->setText(toqstr(post));
676 QModelIndexList qmil =
677 selected_model_.match(selected_model_.index(0, 1),
678 Qt::DisplayRole, toqstr(key), 1,
679 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
681 selected_model_.setItem(qmil.front().row(), 2, si);
686 vector<docstring> GuiCitation::getPostTexts()
688 vector<docstring> res;
689 for (int i = 0; i != selected_model_.rowCount(); ++i) {
690 QStandardItem const * key = selected_model_.item(i, 1);
691 QStandardItem const * post = selected_model_.item(i, 2);
693 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(post->text()));
699 void GuiCitation::init()
701 // Make the list of all available bibliography keys
702 BiblioInfo const & bi = bibInfo();
703 all_keys_ = to_qstring_list(bi.getKeys());
705 available_model_.setStringList(all_keys_);
707 // Ditto for the keys cited in this inset
708 QString str = toqstr(params_["key"]);
712 cited_keys_ = str.split(",");
713 setSelectedKeys(cited_keys_);
715 // Initialize the drop downs
719 // Initialize the citation formatting
720 string const & cmd = params_.getCmdName();
721 CitationStyle const cs =
722 citationStyleFromString(cmd, documentBuffer().params());
724 forceuppercaseCB->setChecked(cs.forceUpperCase);
725 starredCB->setChecked(cs.hasStarredVersion &&
726 documentBuffer().params().fullAuthorList());
727 textBeforeED->setText(toqstr(params_["before"]));
728 textAfterED->setText(toqstr(params_["after"]));
730 setPreTexts(getVectorFromString(params_["pretextlist"], from_ascii("\t")));
731 setPostTexts(getVectorFromString(params_["posttextlist"], from_ascii("\t")));
733 // Update the interface
736 if (selected_model_.rowCount()) {
737 selectedLV->blockSignals(true);
738 selectedLV->setFocus();
739 selectedLV->selectRow(0);
740 selectedLV->blockSignals(false);
742 // Find the citation style
743 vector<string> const & cmds = citeCmds_;
744 vector<string>::const_iterator cit =
745 std::find(cmds.begin(), cmds.end(), cs.name);
747 if (cit != cmds.end())
748 i = int(cit - cmds.begin());
750 // Set the style combo appropriately
751 citationStyleCO->blockSignals(true);
752 citationStyleCO->setCurrentIndex(i);
753 citationStyleCO->blockSignals(false);
754 updateFormatting(citeStyles_[i]);
756 availableLV->setFocus();
758 applyPB->setEnabled(false);
759 okPB->setEnabled(false);
763 void GuiCitation::findKey(BiblioInfo const & bi,
764 QString const & str, bool only_keys,
765 docstring field, docstring entry_type,
766 bool case_sensitive, bool reg_exp, bool reset)
769 // This should be moved to a class member.
770 // Used for optimisation: store last searched string.
771 static QString last_searched_string;
772 // Used to disable the above optimisation.
773 static bool last_case_sensitive;
774 static bool last_reg_exp;
775 // Reset last_searched_string in case of changed option.
776 if (last_case_sensitive != case_sensitive
777 || last_reg_exp != reg_exp) {
778 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
779 last_searched_string.clear();
781 // save option for next search.
782 last_case_sensitive = case_sensitive;
783 last_reg_exp = reg_exp;
785 Qt::CaseSensitivity qtcase = case_sensitive ?
786 Qt::CaseSensitive: Qt::CaseInsensitive;
788 // If new string (str) contains the last searched one...
790 !last_searched_string.isEmpty() &&
792 str.contains(last_searched_string, qtcase))
793 // ... then only search within already found list.
794 keys = available_model_.stringList();
796 // ... else search all keys.
798 // save searched string for next search.
799 last_searched_string = str;
803 // First, filter by entry_type, which will be faster than
804 // what follows, so we may get to do that on less.
805 vector<docstring> keyVector = to_docstring_vector(keys);
806 filterByEntryType(bi, keyVector, entry_type);
809 result = to_qstring_list(keyVector);
811 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
812 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
814 available_model_.setStringList(result);
818 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
820 vector<docstring> const keys = to_docstring_vector(cited_keys_);
821 vector<CitationStyle> styles = citeStyles_;
822 int ind = citationStyleCO->currentIndex();
825 CitationStyle cs = styles[ind];
826 vector<docstring> pretexts = getPreTexts();
827 vector<docstring> posttexts = getPostTexts();
828 bool const qualified = cs.hasQualifiedList
829 && (selectedLV->model()->rowCount() > 1
831 || !posttexts.empty());
832 std::map<docstring, docstring> pres;
833 for (docstring const & s: pretexts) {
835 docstring val = split(s, key, ' ');
838 std::map<docstring, docstring> posts;
839 for (docstring const & s: posttexts) {
841 docstring val = split(s, key, ' ');
845 ci.textBefore = qstring_to_ucs4(textBeforeED->text());
846 ci.textAfter = qstring_to_ucs4(textAfterED->text());
847 ci.forceUpperCase = forceuppercaseCB->isChecked();
848 ci.Starred = starredCB->isChecked();
849 ci.context = CiteItem::Dialog;
850 ci.max_size = max_size;
851 ci.isQualified = qualified;
853 ci.posttexts = posts;
854 vector<docstring> ret = bi.getCiteStrings(keys, styles, documentBuffer(), ci);
855 return to_qstring_list(ret);
859 void GuiCitation::setCitedKeys()
861 cited_keys_ = selectedKeys();
866 bool GuiCitation::initialiseParams(string const & data)
868 InsetCommand::string2params(data, params_);
869 citeCmds_ = documentBuffer().params().citeCommands();
870 citeStyles_ = documentBuffer().params().citeStyles();
876 void GuiCitation::clearParams()
882 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
883 vector<docstring> & keyVector, docstring entry_type)
885 if (entry_type.empty())
888 vector<docstring>::iterator it = keyVector.begin();
889 vector<docstring>::iterator end = keyVector.end();
891 vector<docstring> result;
892 for (; it != end; ++it) {
893 docstring const key = *it;
894 BiblioInfo::const_iterator cit = bi.find(key);
897 if (cit->second.entryType() == entry_type)
898 result.push_back(key);
904 // Escape special chars.
905 // All characters are literals except: '.|*?+(){}[]^$\'
906 // These characters are literals when preceded by a "\", which is done here
907 // @todo: This function should be moved to support, and then the test in tests
908 // should be moved there as well.
909 static docstring escape_special_chars(docstring const & expr)
911 // Search for all chars '.|*?+(){}[^$]\'
912 // Note that '[', ']', and '\' must be escaped.
913 static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
915 // $& is an ECMAScript format expression that expands to all
916 // of the current match
917 #ifdef LYX_USE_STD_REGEX
918 // To prefix a matched expression with a single literal backslash, we
919 // need to escape it for the C++ compiler and use:
921 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
923 // A backslash in the format string starts an escape sequence in boost.
924 // Thus, to prefix a matched expression with a single literal backslash,
925 // we need to give two backslashes to the regex engine, and escape both
926 // for the C++ compiler and use:
928 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
933 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
934 vector<docstring> const & keys_to_search, bool only_keys,
935 docstring const & search_expression, docstring field,
936 bool case_sensitive, bool regex)
938 vector<docstring> foundKeys;
940 docstring expr = trim(search_expression);
945 // We must escape special chars in the search_expr so that
946 // it is treated as a simple string by lyx::regex.
947 expr = escape_special_chars(expr);
951 reg_exp.assign(to_utf8(expr), case_sensitive ?
952 lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
953 } catch (lyx::regex_error const & e) {
954 // lyx::regex throws an exception if the regular expression is not
956 LYXERR(Debug::GUI, e.what());
957 return vector<docstring>();
960 vector<docstring>::const_iterator it = keys_to_search.begin();
961 vector<docstring>::const_iterator end = keys_to_search.end();
962 for (; it != end; ++it ) {
963 BiblioInfo::const_iterator info = bi.find(*it);
964 if (info == bi.end())
967 BibTeXInfo const & kvm = info->second;
971 else if (field.empty())
972 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
974 data = to_utf8(kvm[field]);
980 if (lyx::regex_search(data, reg_exp))
981 foundKeys.push_back(*it);
983 catch (lyx::regex_error const & e) {
984 LYXERR(Debug::GUI, e.what());
985 return vector<docstring>();
992 void GuiCitation::dispatchParams()
994 std::string const lfun = InsetCommand::params2string(params_);
995 dispatch(FuncRequest(getLfun(), lfun));
999 BiblioInfo const & GuiCitation::bibInfo() const
1001 Buffer const & buf = documentBuffer();
1002 buf.reloadBibInfoCache();
1003 return buf.masterBibInfo();
1007 void GuiCitation::saveSession() const
1009 Dialog::saveSession();
1012 sessionKey() + "/regex", regexp_->isChecked());
1014 sessionKey() + "/casesensitive", casesense_->isChecked());
1016 sessionKey() + "/autofind", instant_->isChecked());
1018 sessionKey() + "/citestyle", style_);
1022 void GuiCitation::restoreSession()
1024 Dialog::restoreSession();
1026 regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
1027 casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
1028 instant_->setChecked(settings.value(sessionKey() + "/autofind").toBool());
1029 style_ = settings.value(sessionKey() + "/citestyle").toInt();
1034 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
1037 } // namespace frontend
1040 #include "moc_GuiCitation.cpp"