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_(0), 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());
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::updateControls()
240 BiblioInfo const & bi = bibInfo();
245 // The main point of separating this out is that the fill*() methods
246 // called in update() do not need to be called for INTERNAL updates,
247 // such as when addPB is pressed, as the list of fields, entries, etc,
248 // will not have changed.
249 void GuiCitation::updateControls(BiblioInfo const & bi)
251 QModelIndex idx = selectionManager->getSelectedIndex(1);
253 int i = citationStyleCO->currentIndex();
256 updateFormatting(citeStyles_[i]);
257 selectionManager->update();
261 void GuiCitation::updateFormatting(CitationStyle const & currentStyle)
263 BufferParams const bp = documentBuffer().params();
264 bool const force = currentStyle.forceUpperCase;
265 bool const starred = currentStyle.hasStarredVersion;
266 bool const full = starred && bp.fullAuthorList();
267 bool const textbefore = currentStyle.textBefore;
268 bool const textafter = currentStyle.textAfter;
270 int const rows = selectedLV->model()->rowCount();
272 bool const qualified = currentStyle.hasQualifiedList
274 || !params_["pretextlist"].empty()
275 || !params_["posttextlist"].empty());
276 selectedLV->horizontalHeader()->setVisible(qualified);
277 selectedLV->setColumnHidden(0, !qualified);
278 selectedLV->setColumnHidden(2, !qualified);
279 bool const haveSelection = rows > 0;
281 textBeforeLA->setText(qt_("General text befo&re:"));
282 textAfterLA->setText(qt_("General &text after:"));
283 textBeforeED->setToolTip(qt_("Text that precedes the whole reference list. "
284 "For text that precedes individual items, "
285 "double-click on the respective entry above."));
286 textAfterLA->setToolTip(qt_("General &text after:"));
287 textAfterED->setToolTip(qt_("Text that follows the whole reference list. "
288 "For text that follows individual items, "
289 "double-click on the respective entry above."));
291 textBeforeLA->setText(qt_("Text befo&re:"));
292 if (textbefore && haveSelection)
293 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\")"));
295 textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\"), "
296 "if the current citation style supports this."));
297 textAfterLA->setText(qt_("&Text after:"));
298 if (textafter && haveSelection)
299 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages)"));
301 textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages), "
302 "if the current citation style supports this."));
305 forceuppercaseCB->setEnabled(force && haveSelection);
306 if (force && haveSelection)
307 forceuppercaseCB->setToolTip("Force upper case in names (\"Del Piero\", not \"del Piero\").");
309 forceuppercaseCB->setToolTip("Force upper case in names (\"Del Piero\", not \"del Piero\"), "
310 "if the current citation style supports this.");
311 starredCB->setEnabled(full && haveSelection);
312 textBeforeED->setEnabled(textbefore && haveSelection);
313 textBeforeLA->setEnabled(textbefore && haveSelection);
314 textAfterED->setEnabled(textafter && haveSelection);
315 textAfterLA->setEnabled(textafter && haveSelection);
316 literalCB->setEnabled(textbefore || textafter);
317 citationStyleCO->setEnabled(haveSelection);
318 citationStyleLA->setEnabled(haveSelection);
320 // Check if we have a custom string/tooltip for the starred version
321 if (starred && !currentStyle.stardesc.empty()) {
323 bp.documentClass().getCiteMacro(bp.citeEngineType(), currentStyle.stardesc);
326 guistring = translateIfPossible(from_utf8(val));
327 starredCB->setText(toqstr(guistring));
328 starredCB->setEnabled(haveSelection);
330 if (!currentStyle.startooltip.empty()) {
331 val = bp.documentClass().getCiteMacro(bp.citeEngineType(),
332 currentStyle.startooltip);
334 guistring = translateIfPossible(from_utf8(val));
336 // Tooltip might also be empty
337 starredCB->setToolTip(toqstr(guistring));
339 // This is the default meaning of the starred commands
340 starredCB->setText(qt_("All aut&hors"));
341 if (full && haveSelection)
342 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\")"));
344 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\"), "
345 "if the current citation style supports this."));
350 // Update the styles for the style combo, citationStyleCO, and mark the
351 // settings as changed. Called upon changing the cited keys (including
352 // merely reordering the keys) or editing the text before/after fields.
353 void GuiCitation::updateStyles()
355 BiblioInfo const & bi = bibInfo();
361 // Update the styles for the style combo, citationStyleCO.
362 void GuiCitation::updateStyles(BiblioInfo const & bi)
364 QStringList selected_keys = selectedKeys();
365 int curr = selectedLV->model()->rowCount() - 1;
367 if (curr < 0 || selected_keys.empty()) {
368 citationStyleCO->clear();
369 citationStyleCO->setEnabled(false);
370 citationStyleLA->setEnabled(false);
374 static const size_t max_length = 80;
375 QStringList sty = citationStyles(bi, max_length);
379 citationStyleCO->setEnabled(false);
380 citationStyleLA->setEnabled(false);
381 citationStyleCO->clear();
385 citationStyleCO->blockSignals(true);
388 int const curindex = citationStyleCO->currentIndex();
389 int const oldIndex = (curindex < 0) ? style_ : curindex;
390 citationStyleCO->clear();
391 citationStyleCO->insertItems(0, sty);
392 citationStyleCO->setEnabled(true);
393 citationStyleLA->setEnabled(true);
395 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
396 citationStyleCO->setCurrentIndex(oldIndex);
398 citationStyleCO->blockSignals(false);
402 void GuiCitation::fillFields(BiblioInfo const & bi)
404 fieldsCO->blockSignals(true);
405 int const oldIndex = fieldsCO->currentIndex();
407 QStringList const fields = to_qstring_list(bi.getFields());
408 fieldsCO->insertItem(0, qt_("All fields"));
409 fieldsCO->insertItem(1, qt_("Keys"));
410 fieldsCO->insertItems(2, fields);
411 if (oldIndex != -1 && oldIndex < fieldsCO->count())
412 fieldsCO->setCurrentIndex(oldIndex);
413 fieldsCO->blockSignals(false);
417 void GuiCitation::fillEntries(BiblioInfo const & bi)
419 entriesCO->blockSignals(true);
420 int const oldIndex = entriesCO->currentIndex();
422 QStringList const entries = to_qstring_list(bi.getEntries());
423 entriesCO->insertItem(0, qt_("All entry types"));
424 entriesCO->insertItems(1, entries);
425 if (oldIndex != -1 && oldIndex < entriesCO->count())
426 entriesCO->setCurrentIndex(oldIndex);
427 entriesCO->blockSignals(false);
431 bool GuiCitation::isSelected(QModelIndex const & idx)
433 QString const str = idx.data().toString();
434 return selectedKeys().contains(str);
438 void GuiCitation::setButtons()
440 int const srows = selectedLV->model()->rowCount();
441 applyPB->setEnabled(srows > 0);
442 okPB->setEnabled(srows > 0);
446 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
448 if (!idx.isValid() || bi.empty()) {
449 infoML->document()->clear();
450 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
454 infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
457 QString const keytxt = toqstr(
458 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), ci));
459 infoML->document()->setHtml(keytxt);
463 void GuiCitation::findText(QString const & text, bool reset)
465 //"All Fields" and "Keys" are the first two
466 int index = fieldsCO->currentIndex() - 2;
467 BiblioInfo const & bi = bibInfo();
468 vector<docstring> const & fields = bi.getFields();
471 if (index <= -1 || index >= int(fields.size()))
472 //either "All Fields" or "Keys" or an invalid value
473 field = from_ascii("");
475 field = fields[index];
478 bool const onlyKeys = index == -1;
480 //"All Entry Types" is first.
481 index = entriesCO->currentIndex() - 1;
482 vector<docstring> const & entries = bi.getEntries();
483 docstring entry_type;
484 if (index < 0 || index >= int(entries.size()))
485 entry_type = from_ascii("");
487 entry_type = entries[index];
489 bool const case_sentitive = casesense_->isChecked();
490 bool const reg_exp = regexp_->isChecked();
492 findKey(bi, text, onlyKeys, field, entry_type,
493 case_sentitive, reg_exp, reset);
495 //It'd be nice to save and restore the current selection in
496 //availableLV. Currently, we get an automatic reset, since the
503 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
505 findText(filter_->text(), true);
509 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
511 findText(filter_->text(), true);
515 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
517 if (index >= 0 && index < citationStyleCO->count()) {
518 vector<CitationStyle> const & styles = citeStyles_;
519 updateFormatting(styles[index]);
525 void GuiCitation::filterChanged(const QString & text)
527 if (!text.isEmpty()) {
528 if (instant_->isChecked())
529 findText(filter_->text());
532 findText(filter_->text());
537 void GuiCitation::filterPressed()
539 findText(filter_->text(), true);
543 void GuiCitation::resetFilter()
545 filter_->setText(QString());
546 findText(filter_->text(), true);
550 void GuiCitation::caseChanged()
552 findText(filter_->text());
556 void GuiCitation::regexChanged()
558 findText(filter_->text());
562 void GuiCitation::updateFilterHint()
564 QString const hint = instant_->isChecked() ?
565 qt_("Enter string to filter the list of available citations") :
566 qt_("Enter string to filter the list of available citations and press <Enter>");
567 filter_->setToolTip(hint);
571 void GuiCitation::instantChanged(bool checked)
574 findText(filter_->text(), true);
580 void GuiCitation::changed()
586 void GuiCitation::applyParams(int const choice, bool full, bool force,
587 QString before, QString after)
589 if (cited_keys_.isEmpty())
592 vector<CitationStyle> const & styles = citeStyles_;
594 CitationStyle cs = styles[choice];
601 cs.forceUpperCase &= force;
602 cs.hasStarredVersion &= full;
603 string const command = citationStyleToString(cs);
605 params_.setCmdName(command);
606 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
607 params_["before"] = qstring_to_ucs4(before);
608 params_["after"] = qstring_to_ucs4(after);
609 if (cs.hasQualifiedList) {
610 params_["pretextlist"] = getStringFromVector(getPreTexts(), from_ascii("\t"));
611 params_["posttextlist"] = getStringFromVector(getPostTexts(), from_ascii("\t"));
613 params_["literal"] = literalCB->isChecked() ? from_ascii("true") : from_ascii("false");
618 void GuiCitation::clearSelection()
621 setSelectedKeys(cited_keys_);
625 void GuiCitation::setSelectedKeys(QStringList const sl)
627 selected_model_.clear();
628 selected_model_.setColumnCount(3);
630 headers << qt_("Text before")
632 << qt_("Text after");
633 selected_model_.setHorizontalHeaderLabels(headers);
634 selectedLV->setColumnHidden(0, true);
635 selectedLV->setColumnHidden(2, true);
636 selectedLV->verticalHeader()->setVisible(false);
637 selectedLV->horizontalHeader()->setVisible(false);
638 QStringList::const_iterator it = sl.begin();
639 QStringList::const_iterator end = sl.end();
640 for (int i = 0; it != end; ++it, ++i) {
641 QStandardItem * si = new QStandardItem();
645 si->setEditable(false);
646 selected_model_.setItem(i, 1, si);
651 QStringList GuiCitation::selectedKeys()
654 for (int i = 0; i != selected_model_.rowCount(); ++i) {
655 QStandardItem const * item = selected_model_.item(i, 1);
657 res.append(item->text());
663 void GuiCitation::setPreTexts(vector<docstring> const m)
665 for (docstring const & s: m) {
666 QStandardItem * si = new QStandardItem();
668 docstring pre = split(s, key, ' ');
669 si->setData(toqstr(pre));
670 si->setText(toqstr(pre));
671 QModelIndexList qmil =
672 selected_model_.match(selected_model_.index(0, 1),
673 Qt::DisplayRole, toqstr(key), 1,
674 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
676 selected_model_.setItem(qmil.front().row(), 0, si);
681 vector<docstring> GuiCitation::getPreTexts()
683 vector<docstring> res;
684 for (int i = 0; i != selected_model_.rowCount(); ++i) {
685 QStandardItem const * key = selected_model_.item(i, 1);
686 QStandardItem const * pre = selected_model_.item(i, 0);
687 if (key && pre && !key->text().isEmpty() && !pre->text().isEmpty())
688 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(pre->text()));
694 void GuiCitation::setPostTexts(vector<docstring> const m)
696 for (docstring const & s: m) {
697 QStandardItem * si = new QStandardItem();
699 docstring post = split(s, key, ' ');
700 si->setData(toqstr(post));
701 si->setText(toqstr(post));
702 QModelIndexList qmil =
703 selected_model_.match(selected_model_.index(0, 1),
704 Qt::DisplayRole, toqstr(key), 1,
705 Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
707 selected_model_.setItem(qmil.front().row(), 2, si);
712 vector<docstring> GuiCitation::getPostTexts()
714 vector<docstring> res;
715 for (int i = 0; i != selected_model_.rowCount(); ++i) {
716 QStandardItem const * key = selected_model_.item(i, 1);
717 QStandardItem const * post = selected_model_.item(i, 2);
719 res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(post->text()));
725 void GuiCitation::init()
727 // Make the list of all available bibliography keys
728 BiblioInfo const & bi = bibInfo();
729 all_keys_ = to_qstring_list(bi.getKeys());
731 available_model_.setStringList(all_keys_);
733 // Ditto for the keys cited in this inset
734 QString str = toqstr(params_["key"]);
738 cited_keys_ = str.split(",");
739 setSelectedKeys(cited_keys_);
741 // Initialize the drop downs
745 // Initialize the citation formatting
746 string const & cmd = params_.getCmdName();
747 CitationStyle const cs =
748 citationStyleFromString(cmd, documentBuffer().params());
750 forceuppercaseCB->setChecked(cs.forceUpperCase);
751 starredCB->setChecked(cs.hasStarredVersion &&
752 documentBuffer().params().fullAuthorList());
753 textBeforeED->setText(toqstr(params_["before"]));
754 textAfterED->setText(toqstr(params_["after"]));
755 literalCB->setChecked(params_["literal"] == "true");
757 setPreTexts(getVectorFromString(params_["pretextlist"], from_ascii("\t")));
758 setPostTexts(getVectorFromString(params_["posttextlist"], from_ascii("\t")));
760 // Update the interface
763 if (selected_model_.rowCount()) {
764 selectedLV->blockSignals(true);
765 selectedLV->setFocus();
766 selectedLV->selectRow(0);
767 selectedLV->blockSignals(false);
769 // Find the citation style
770 vector<string> const & cmds = citeCmds_;
771 vector<string>::const_iterator cit =
772 std::find(cmds.begin(), cmds.end(), cs.name);
774 if (cit != cmds.end())
775 i = int(cit - cmds.begin());
777 // Set the style combo appropriately
778 citationStyleCO->blockSignals(true);
779 citationStyleCO->setCurrentIndex(i);
780 citationStyleCO->blockSignals(false);
781 updateFormatting(citeStyles_[i]);
783 availableLV->setFocus();
785 applyPB->setEnabled(false);
786 okPB->setEnabled(false);
790 void GuiCitation::findKey(BiblioInfo const & bi,
791 QString const & str, bool only_keys,
792 docstring field, docstring entry_type,
793 bool case_sensitive, bool reg_exp, bool reset)
796 // This should be moved to a class member.
797 // Used for optimisation: store last searched string.
798 static QString last_searched_string;
799 // Used to disable the above optimisation.
800 static bool last_case_sensitive;
801 static bool last_reg_exp;
802 // Reset last_searched_string in case of changed option.
803 if (last_case_sensitive != case_sensitive
804 || last_reg_exp != reg_exp) {
805 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
806 last_searched_string.clear();
808 // save option for next search.
809 last_case_sensitive = case_sensitive;
810 last_reg_exp = reg_exp;
812 Qt::CaseSensitivity qtcase = case_sensitive ?
813 Qt::CaseSensitive: Qt::CaseInsensitive;
815 // If new string (str) contains the last searched one...
817 !last_searched_string.isEmpty() &&
819 str.contains(last_searched_string, qtcase))
820 // ... then only search within already found list.
821 keys = available_model_.stringList();
823 // ... else search all keys.
825 // save searched string for next search.
826 last_searched_string = str;
830 // First, filter by entry_type, which will be faster than
831 // what follows, so we may get to do that on less.
832 vector<docstring> keyVector = to_docstring_vector(keys);
833 filterByEntryType(bi, keyVector, entry_type);
836 result = to_qstring_list(keyVector);
838 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
839 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
841 available_model_.setStringList(result);
845 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
847 vector<docstring> const keys = to_docstring_vector(cited_keys_);
848 vector<CitationStyle> styles = citeStyles_;
849 int ind = citationStyleCO->currentIndex();
852 CitationStyle cs = styles[ind];
853 vector<docstring> pretexts = getPreTexts();
854 vector<docstring> posttexts = getPostTexts();
855 bool const qualified = cs.hasQualifiedList
856 && (selectedLV->model()->rowCount() > 1
858 || !posttexts.empty());
859 std::map<docstring, docstring> pres;
860 for (docstring const & s: pretexts) {
862 docstring val = split(s, key, ' ');
865 std::map<docstring, docstring> posts;
866 for (docstring const & s: posttexts) {
868 docstring val = split(s, key, ' ');
872 ci.textBefore = qstring_to_ucs4(textBeforeED->text());
873 ci.textAfter = qstring_to_ucs4(textAfterED->text());
874 ci.forceUpperCase = forceuppercaseCB->isChecked();
875 ci.Starred = starredCB->isChecked();
876 ci.context = CiteItem::Dialog;
877 ci.max_size = max_size;
878 ci.isQualified = qualified;
880 ci.posttexts = posts;
881 vector<docstring> ret = bi.getCiteStrings(keys, styles, documentBuffer(), ci);
882 return to_qstring_list(ret);
886 void GuiCitation::setCitedKeys()
888 cited_keys_ = selectedKeys();
893 bool GuiCitation::initialiseParams(string const & data)
895 InsetCommand::string2params(data, params_);
896 citeCmds_ = documentBuffer().params().citeCommands();
897 citeStyles_ = documentBuffer().params().citeStyles();
903 void GuiCitation::clearParams()
909 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
910 vector<docstring> & keyVector, docstring entry_type)
912 if (entry_type.empty())
915 vector<docstring>::iterator it = keyVector.begin();
916 vector<docstring>::iterator end = keyVector.end();
918 vector<docstring> result;
919 for (; it != end; ++it) {
920 docstring const key = *it;
921 BiblioInfo::const_iterator cit = bi.find(key);
924 if (cit->second.entryType() == entry_type)
925 result.push_back(key);
931 // Escape special chars.
932 // All characters are literals except: '.|*?+(){}[]^$\'
933 // These characters are literals when preceded by a "\", which is done here
934 // @todo: This function should be moved to support, and then the test in tests
935 // should be moved there as well.
936 static docstring escape_special_chars(docstring const & expr)
938 // Search for all chars '.|*?+(){}[^$]\'
939 // Note that '[', ']', and '\' must be escaped.
940 static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
942 // $& is an ECMAScript format expression that expands to all
943 // of the current match
944 #ifdef LYX_USE_STD_REGEX
945 // To prefix a matched expression with a single literal backslash, we
946 // need to escape it for the C++ compiler and use:
948 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
950 // A backslash in the format string starts an escape sequence in boost.
951 // Thus, to prefix a matched expression with a single literal backslash,
952 // we need to give two backslashes to the regex engine, and escape both
953 // for the C++ compiler and use:
955 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
960 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
961 vector<docstring> const & keys_to_search, bool only_keys,
962 docstring const & search_expression, docstring field,
963 bool case_sensitive, bool regex)
965 vector<docstring> foundKeys;
967 docstring expr = trim(search_expression);
972 // We must escape special chars in the search_expr so that
973 // it is treated as a simple string by lyx::regex.
974 expr = escape_special_chars(expr);
978 reg_exp.assign(to_utf8(expr), case_sensitive ?
979 lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
980 } catch (lyx::regex_error const & e) {
981 // lyx::regex throws an exception if the regular expression is not
983 LYXERR(Debug::GUI, e.what());
984 return vector<docstring>();
987 vector<docstring>::const_iterator it = keys_to_search.begin();
988 vector<docstring>::const_iterator end = keys_to_search.end();
989 for (; it != end; ++it ) {
990 BiblioInfo::const_iterator info = bi.find(*it);
991 if (info == bi.end())
994 BibTeXInfo const & kvm = info->second;
998 else if (field.empty())
999 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
1001 data = to_utf8(kvm[field]);
1007 if (lyx::regex_search(data, reg_exp))
1008 foundKeys.push_back(*it);
1010 catch (lyx::regex_error const & e) {
1011 LYXERR(Debug::GUI, e.what());
1012 return vector<docstring>();
1019 void GuiCitation::dispatchParams()
1021 std::string const lfun = InsetCommand::params2string(params_);
1022 dispatch(FuncRequest(getLfun(), lfun));
1026 BiblioInfo const & GuiCitation::bibInfo() const
1028 Buffer const & buf = documentBuffer();
1029 buf.reloadBibInfoCache();
1030 return buf.masterBibInfo();
1034 void GuiCitation::saveSession() const
1036 Dialog::saveSession();
1039 sessionKey() + "/regex", regexp_->isChecked());
1041 sessionKey() + "/casesensitive", casesense_->isChecked());
1043 sessionKey() + "/autofind", instant_->isChecked());
1045 sessionKey() + "/citestyle", style_);
1049 void GuiCitation::restoreSession()
1051 Dialog::restoreSession();
1053 regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
1054 casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
1055 instant_->setChecked(settings.value(sessionKey() + "/autofind", true).toBool());
1056 style_ = settings.value(sessionKey() + "/citestyle").toInt();
1061 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
1064 } // namespace frontend
1067 #include "moc_GuiCitation.cpp"