2 * \file GuiCitation.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
7 * \author Kalle Dalheimer
8 * \author Abdelrazak Younes
11 * Full author contact details are available in file CREDITS.
16 #include "GuiCitation.h"
18 #include "support/debug.h"
19 #include "support/gettext.h"
20 #include "qt_helpers.h"
22 #include "BufferParams.h"
24 #include "support/lstrings.h"
25 #include "support/docstring.h"
27 #include "insets/InsetCommand.h"
32 #include <QCloseEvent>
37 #include <boost/regex.hpp>
48 static vector<biblio::CiteStyle> citeStyles_;
51 template<typename String>
52 static QStringList to_qstring_list(vector<String> const & v)
56 for (size_t i = 0; i != v.size(); ++i) {
59 qlist.append(lyx::toqstr(v[i]));
65 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
67 vector<lyx::docstring> v;
68 for (int i = 0; i != qlist.size(); ++i) {
69 if (qlist[i].isEmpty())
71 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
77 GuiCitation::GuiCitation(GuiView & lv)
78 : GuiCommand(lv, "citation")
81 setViewTitle(_("Citation"));
83 connect(citationStyleCO, SIGNAL(activated(int)),
84 this, SLOT(changed()));
85 connect(fulllistCB, SIGNAL(clicked()),
86 this, SLOT(changed()));
87 connect(forceuppercaseCB, SIGNAL(clicked()),
88 this, SLOT(changed()));
89 connect(textBeforeED, SIGNAL(textChanged(QString)),
90 this, SLOT(changed()));
91 connect(textAfterED, SIGNAL(textChanged(QString)),
92 this, SLOT(changed()));
93 connect(clearPB, SIGNAL(clicked()),
94 findLE, SLOT(clear()));
95 connect(this, SIGNAL(rejected()), this, SLOT(cleanUp()));
97 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
98 addPB, deletePB, upPB, downPB, available(), selected());
99 connect(selectionManager, SIGNAL(selectionChanged()),
100 this, SLOT(setCitedKeys()));
101 connect(selectionManager, SIGNAL(updateHook()),
102 this, SLOT(updateDialog()));
103 connect(selectionManager, SIGNAL(okHook()),
104 this, SLOT(on_okPB_clicked()));
106 bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
110 void GuiCitation::cleanUp()
118 void GuiCitation::closeEvent(QCloseEvent * e)
122 GuiDialog::closeEvent(e);
126 void GuiCitation::applyView()
128 int const choice = std::max(0, citationStyleCO->currentIndex());
130 bool const full = fulllistCB->isChecked();
131 bool const force = forceuppercaseCB->isChecked();
133 QString const before = textBeforeED->text();
134 QString const after = textAfterED->text();
136 apply(choice, full, force, before, after);
140 void GuiCitation::showEvent(QShowEvent * e)
144 availableLV->setFocus();
145 GuiDialog::showEvent(e);
149 void GuiCitation::on_okPB_clicked()
157 void GuiCitation::on_cancelPB_clicked()
164 void GuiCitation::on_applyPB_clicked()
170 void GuiCitation::on_restorePB_clicked()
177 void GuiCitation::updateView()
186 // The main point of separating this out is that the fill*() methods
187 // called in update() do not need to be called for INTERNAL updates,
188 // such as when addPB is pressed, as the list of fields, entries, etc,
189 // will not have changed. At the moment, however, the division between
190 // fillStyles() and updateStyles() doesn't lend itself to dividing the
191 // two methods, though they should be divisible.
192 void GuiCitation::updateDialog()
194 if (selectionManager->selectedFocused()) {
195 if (selectedLV->selectionModel()->selectedIndexes().isEmpty())
196 updateInfo(availableLV->currentIndex());
198 updateInfo(selectedLV->currentIndex());
200 if (availableLV->selectionModel()->selectedIndexes().isEmpty())
201 updateInfo(QModelIndex());
203 updateInfo(availableLV->currentIndex());
207 textBeforeED->setText(textBefore());
208 textAfterED->setText(textAfter());
214 void GuiCitation::updateStyle()
216 biblio::CiteEngine const engine = getEngine();
217 bool const natbib_engine =
218 engine == biblio::ENGINE_NATBIB_AUTHORYEAR ||
219 engine == biblio::ENGINE_NATBIB_NUMERICAL;
220 bool const basic_engine = engine == biblio::ENGINE_BASIC;
222 bool const haveSelection =
223 selectedLV->model()->rowCount() > 0;
224 fulllistCB->setEnabled(natbib_engine && haveSelection);
225 forceuppercaseCB->setEnabled(natbib_engine && haveSelection);
226 textBeforeED->setEnabled(!basic_engine && haveSelection);
227 textBeforeLA->setEnabled(!basic_engine && haveSelection);
228 textAfterED->setEnabled(haveSelection);
229 textAfterLA->setEnabled(haveSelection);
230 citationStyleCO->setEnabled(!basic_engine && haveSelection);
231 citationStyleLA->setEnabled(!basic_engine && haveSelection);
233 string const & command = params_.getCmdName();
235 // Find the style of the citekeys
236 vector<biblio::CiteStyle> const & styles = citeStyles_;
237 biblio::CitationStyle const cs(command);
239 vector<biblio::CiteStyle>::const_iterator cit =
240 std::find(styles.begin(), styles.end(), cs.style);
242 // restore the latest natbib style
243 if (style_ >= 0 && style_ < citationStyleCO->count())
244 citationStyleCO->setCurrentIndex(style_);
246 citationStyleCO->setCurrentIndex(0);
248 if (cit != styles.end()) {
249 int const i = int(cit - styles.begin());
250 citationStyleCO->setCurrentIndex(i);
251 fulllistCB->setChecked(cs.full);
252 forceuppercaseCB->setChecked(cs.forceUCase);
254 fulllistCB->setChecked(false);
255 forceuppercaseCB->setChecked(false);
260 //This one needs to be called whenever citationStyleCO needs
261 //to be updated---and this would be on anything that changes the
262 //selection in selectedLV, or on a general update.
263 void GuiCitation::fillStyles()
265 int const oldIndex = citationStyleCO->currentIndex();
267 citationStyleCO->clear();
269 QStringList selected_keys = selected()->stringList();
270 if (selected_keys.empty()) {
271 citationStyleCO->setEnabled(false);
272 citationStyleLA->setEnabled(false);
276 int curr = selectedLV->model()->rowCount() - 1;
280 if (!selectedLV->selectionModel()->selectedIndexes().empty())
281 curr = selectedLV->selectionModel()->selectedIndexes()[0].row();
283 QStringList sty = citationStyles(curr);
285 bool const basic_engine = (getEngine() == biblio::ENGINE_BASIC);
287 citationStyleCO->setEnabled(!sty.isEmpty() && !basic_engine);
288 citationStyleLA->setEnabled(!sty.isEmpty() && !basic_engine);
290 if (sty.isEmpty() || basic_engine)
293 citationStyleCO->insertItems(0, sty);
295 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
296 citationStyleCO->setCurrentIndex(oldIndex);
300 void GuiCitation::fillFields()
302 fieldsCO->blockSignals(true);
303 int const oldIndex = fieldsCO->currentIndex();
305 QStringList const & fields = getFieldsAsQStringList();
306 fieldsCO->insertItem(0, qt_("All Fields"));
307 fieldsCO->insertItem(1, qt_("Keys"));
308 fieldsCO->insertItems(2, fields);
309 if (oldIndex != -1 && oldIndex < fieldsCO->count())
310 fieldsCO->setCurrentIndex(oldIndex);
311 fieldsCO->blockSignals(false);
315 void GuiCitation::fillEntries()
317 entriesCO->blockSignals(true);
318 int const oldIndex = entriesCO->currentIndex();
320 QStringList const & entries = getEntriesAsQStringList();
321 entriesCO->insertItem(0, qt_("All Entry Types"));
322 entriesCO->insertItems(1, entries);
323 if (oldIndex != -1 && oldIndex < entriesCO->count())
324 entriesCO->setCurrentIndex(oldIndex);
325 entriesCO->blockSignals(false);
329 bool GuiCitation::isSelected(const QModelIndex & idx)
331 QString const str = idx.data().toString();
332 return selected()->stringList().contains(str);
336 void GuiCitation::setButtons()
338 selectionManager->update();
339 int const srows = selectedLV->model()->rowCount();
340 applyPB->setEnabled(srows > 0);
341 okPB->setEnabled(srows > 0);
345 void GuiCitation::updateInfo(QModelIndex const & idx)
348 QString const keytxt = getKeyInfo(idx.data().toString());
349 infoML->document()->setPlainText(keytxt);
351 infoML->document()->clear();
355 void GuiCitation::findText(QString const & text, bool reset)
357 //"All Fields" and "Keys" are the first two
358 int index = fieldsCO->currentIndex() - 2;
359 vector<docstring> const & fields = availableFields();
362 if (index <= -1 || index >= int(fields.size()))
363 //either "All Fields" or "Keys" or an invalid value
364 field = from_ascii("");
366 field = fields[index];
369 bool const onlyKeys = index == -1;
371 //"All Entry Types" is first.
372 index = entriesCO->currentIndex() - 1;
373 vector<docstring> const & entries = availableEntries();
375 if (index < 0 || index >= int(entries.size()))
376 entryType = from_ascii("");
378 entryType = entries[index];
380 bool const case_sentitive = caseCB->checkState();
381 bool const reg_exp = regexCB->checkState();
382 findKey(text, onlyKeys, field, entryType,
383 case_sentitive, reg_exp, reset);
385 //It'd be nice to save and restore the current selection in
386 //availableLV. Currently, we get an automatic reset, since the
393 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
395 findText(findLE->text(), true);
399 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
401 findText(findLE->text(), true);
405 void GuiCitation::on_findLE_textChanged(const QString & text)
407 clearPB->setDisabled(text.isEmpty());
414 void GuiCitation::on_caseCB_stateChanged(int)
416 findText(findLE->text());
420 void GuiCitation::on_regexCB_stateChanged(int)
422 findText(findLE->text());
426 void GuiCitation::changed()
433 void GuiCitation::apply(int const choice, bool const full, bool const force,
434 QString before, QString after)
436 if (cited_keys_.isEmpty())
439 vector<biblio::CiteStyle> const & styles = citeStyles_;
441 string const command =
442 biblio::CitationStyle(styles[choice], full, force)
445 params_.setCmdName(command);
446 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
447 params_["before"] = qstring_to_ucs4(before);
448 params_["after"] = qstring_to_ucs4(after);
453 void GuiCitation::clearSelection()
456 selected_model_.setStringList(cited_keys_);
460 QString GuiCitation::textBefore()
462 return toqstr(params_["before"]);
466 QString GuiCitation::textAfter()
468 return toqstr(params_["after"]);
472 void GuiCitation::init()
474 // Make the list of all available bibliography keys
475 all_keys_ = to_qstring_list(availableKeys());
476 available_model_.setStringList(all_keys_);
478 // Ditto for the keys cited in this inset
479 QString str = toqstr(params_["key"]);
483 cited_keys_ = str.split(",");
484 selected_model_.setStringList(cited_keys_);
488 void GuiCitation::findKey(QString const & str, bool only_keys,
489 docstring field, docstring entryType,
490 bool case_sensitive, bool reg_exp, bool reset)
492 // Used for optimisation: store last searched string.
493 static QString last_searched_string;
494 // Used to disable the above optimisation.
495 static bool last_case_sensitive;
496 static bool last_reg_exp;
497 // Reset last_searched_string in case of changed option.
498 if (last_case_sensitive != case_sensitive
499 || last_reg_exp != reg_exp) {
500 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
501 last_searched_string.clear();
503 // save option for next search.
504 last_case_sensitive = case_sensitive;
505 last_reg_exp = reg_exp;
507 Qt::CaseSensitivity qtcase = case_sensitive?
508 Qt::CaseSensitive: Qt::CaseInsensitive;
510 // If new string (str) contains the last searched one...
512 !last_searched_string.isEmpty() &&
514 str.contains(last_searched_string, qtcase))
515 // ... then only search within already found list.
516 keys = available_model_.stringList();
518 // ... else search all keys.
520 // save searched string for next search.
521 last_searched_string = str;
525 // First, filter by entryType, which will be faster than
526 // what follows, so we may get to do that on less.
527 vector<docstring> keyVector = to_docstring_vector(keys);
528 filterByEntryType(keyVector, entryType);
531 result = to_qstring_list(keyVector);
533 result = to_qstring_list(searchKeys(keyVector, only_keys,
534 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
536 available_model_.setStringList(result);
540 QStringList GuiCitation::getFieldsAsQStringList()
542 return to_qstring_list(availableFields());
546 QStringList GuiCitation::getEntriesAsQStringList()
548 return to_qstring_list(availableEntries());
552 QStringList GuiCitation::citationStyles(int sel)
554 docstring const key = qstring_to_ucs4(cited_keys_[sel]);
555 return to_qstring_list(bibkeysInfo_.getCiteStrings(key, buffer()));
559 QString GuiCitation::getKeyInfo(QString const & sel)
561 return toqstr(getInfo(qstring_to_ucs4(sel)));
565 void GuiCitation::setCitedKeys()
567 cited_keys_ = selected_model_.stringList();
571 bool GuiCitation::initialiseParams(string const & data)
573 InsetCommandMailer::string2params(lfun_name_, data, params_);
575 biblio::CiteEngine const engine = buffer().params().getEngine();
577 bool use_styles = engine != biblio::ENGINE_BASIC;
579 bibkeysInfo_.fillWithBibKeys(&buffer());
581 if (citeStyles_.empty())
582 citeStyles_ = biblio::getCiteStyles(engine);
584 if ((use_styles && citeStyles_.size() == 1) ||
585 (!use_styles && citeStyles_.size() != 1))
586 citeStyles_ = biblio::getCiteStyles(engine);
593 void GuiCitation::clearParams()
596 bibkeysInfo_.clear();
600 vector<docstring> const GuiCitation::availableKeys() const
602 return bibkeysInfo_.getKeys();
606 vector<docstring> const GuiCitation::availableFields() const
608 return bibkeysInfo_.getFields();
612 vector<docstring> const GuiCitation::availableEntries() const
614 return bibkeysInfo_.getEntries();
618 void GuiCitation::filterByEntryType(
619 vector<docstring> & keyVector, docstring entryType)
621 if (entryType.empty())
624 vector<docstring>::iterator it = keyVector.begin();
625 vector<docstring>::iterator end = keyVector.end();
627 vector<docstring> result;
628 for (; it != end; ++it) {
629 docstring const key = *it;
630 BiblioInfo::const_iterator cit = bibkeysInfo_.find(key);
631 if (cit == bibkeysInfo_.end())
633 if (cit->second.entryType == entryType)
634 result.push_back(key);
640 biblio::CiteEngine GuiCitation::getEngine() const
642 return buffer().params().getEngine();
646 docstring GuiCitation::getInfo(docstring const & key) const
648 if (bibkeysInfo_.empty())
651 return bibkeysInfo_.getInfo(key);
655 // Escape special chars.
656 // All characters are literals except: '.|*?+(){}[]^$\'
657 // These characters are literals when preceded by a "\", which is done here
658 // @todo: This function should be moved to support, and then the test in tests
659 // should be moved there as well.
660 static docstring escape_special_chars(docstring const & expr)
662 // Search for all chars '.|*?+(){}[^$]\'
663 // Note that '[' and '\' must be escaped.
664 // This is a limitation of boost::regex, but all other chars in BREs
665 // are assumed literal.
666 static const boost::regex reg("[].|*?+(){}^$\\[\\\\]");
668 // $& is a perl-like expression that expands to all
669 // of the current match
670 // The '$' must be prefixed with the escape character '\' for
671 // boost to treat it as a literal.
672 // Thus, to prefix a matched expression with '\', we use:
674 return from_utf8(boost::regex_replace(to_utf8(expr), reg, "\\\\$&"));
678 vector<docstring> GuiCitation::searchKeys(
679 vector<docstring> const & keys_to_search, bool only_keys,
680 docstring const & search_expression, docstring field,
681 bool case_sensitive, bool regex)
683 vector<docstring> foundKeys;
685 docstring expr = support::trim(search_expression);
690 // We must escape special chars in the search_expr so that
691 // it is treated as a simple string by boost::regex.
692 expr = escape_special_chars(expr);
694 boost::regex reg_exp(to_utf8(expr), case_sensitive ?
695 boost::regex_constants::normal : boost::regex_constants::icase);
697 vector<docstring>::const_iterator it = keys_to_search.begin();
698 vector<docstring>::const_iterator end = keys_to_search.end();
699 for (; it != end; ++it ) {
700 BiblioInfo::const_iterator info = bibkeysInfo_.find(*it);
701 if (info == bibkeysInfo_.end())
704 BibTeXInfo const & kvm = info->second;
708 else if (field.empty())
709 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData);
710 else if (kvm.hasField(field))
711 data = to_utf8(kvm.getValueForField(field));
717 if (boost::regex_search(data, reg_exp))
718 foundKeys.push_back(*it);
720 catch (boost::regex_error &) {
721 return vector<docstring>();
728 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
731 } // namespace frontend
734 #include "GuiCitation_moc.cpp"