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 "qt_helpers.h"
20 #include "BufferParams.h"
21 #include "FuncRequest.h"
23 #include "insets/InsetCommand.h"
25 #include "support/debug.h"
26 #include "support/docstring.h"
27 #include "support/gettext.h"
28 #include "support/lstrings.h"
30 #include <QCloseEvent>
38 #include <boost/regex.hpp>
45 using namespace lyx::support;
50 static vector<CiteStyle> citeStyles_;
53 template<typename String>
54 static QStringList to_qstring_list(vector<String> const & v)
58 for (size_t i = 0; i != v.size(); ++i) {
61 qlist.append(lyx::toqstr(v[i]));
67 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
69 vector<lyx::docstring> v;
70 for (int i = 0; i != qlist.size(); ++i) {
71 if (qlist[i].isEmpty())
73 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
79 GuiCitation::GuiCitation(GuiView & lv)
80 : GuiDialog(lv, "citation", qt_("Citation")),
81 params_(insetCode("citation"))
85 connect(citationStyleCO, SIGNAL(activated(int)),
86 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
87 connect(fulllistCB, SIGNAL(clicked()),
88 this, SLOT(changed()));
89 connect(forceuppercaseCB, SIGNAL(clicked()),
90 this, SLOT(changed()));
91 connect(textBeforeED, SIGNAL(textChanged(QString)),
92 this, SLOT(changed()));
93 connect(textAfterED, SIGNAL(textChanged(QString)),
94 this, SLOT(changed()));
95 connect(findLE, SIGNAL(returnPressed()),
96 this, SLOT(on_searchPB_clicked()));
97 connect(textBeforeED, SIGNAL(returnPressed()),
98 this, SLOT(on_okPB_clicked()));
99 connect(textAfterED, SIGNAL(returnPressed()),
100 this, SLOT(on_okPB_clicked()));
102 connect(this, SIGNAL(rejected()), this, SLOT(cleanUp()));
104 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
105 addPB, deletePB, upPB, downPB, available(), selected());
106 connect(selectionManager, SIGNAL(selectionChanged()),
107 this, SLOT(setCitedKeys()));
108 connect(selectionManager, SIGNAL(updateHook()),
109 this, SLOT(updateDialog()));
110 connect(selectionManager, SIGNAL(okHook()),
111 this, SLOT(on_okPB_clicked()));
113 bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
117 void GuiCitation::cleanUp()
125 void GuiCitation::closeEvent(QCloseEvent * e)
133 void GuiCitation::applyView()
135 int const choice = max(0, citationStyleCO->currentIndex());
137 bool const full = fulllistCB->isChecked();
138 bool const force = forceuppercaseCB->isChecked();
140 QString const before = textBeforeED->text();
141 QString const after = textAfterED->text();
143 apply(choice, full, force, before, after);
147 void GuiCitation::showEvent(QShowEvent * e)
151 availableLV->setFocus();
152 GuiDialog::showEvent(e);
156 void GuiCitation::on_okPB_clicked()
164 void GuiCitation::on_cancelPB_clicked()
171 void GuiCitation::on_applyPB_clicked()
177 void GuiCitation::on_restorePB_clicked()
184 void GuiCitation::updateView()
193 // The main point of separating this out is that the fill*() methods
194 // called in update() do not need to be called for INTERNAL updates,
195 // such as when addPB is pressed, as the list of fields, entries, etc,
196 // will not have changed. At the moment, however, the division between
197 // fillStyles() and updateStyle() doesn't lend itself to dividing the
198 // two methods, though they should be divisible.
199 void GuiCitation::updateDialog()
201 if (selectionManager->selectedFocused()) {
202 if (selectedLV->selectionModel()->selectedIndexes().isEmpty())
203 updateInfo(availableLV->currentIndex());
205 updateInfo(selectedLV->currentIndex());
207 if (availableLV->selectionModel()->selectedIndexes().isEmpty())
208 updateInfo(QModelIndex());
210 updateInfo(availableLV->currentIndex());
214 textBeforeED->setText(textBefore());
215 textAfterED->setText(textAfter());
221 void GuiCitation::updateFormatting(CiteStyle currentStyle)
223 CiteEngine const engine = citeEngine();
224 bool const natbib_engine =
225 engine == ENGINE_NATBIB_AUTHORYEAR ||
226 engine == ENGINE_NATBIB_NUMERICAL;
227 bool const basic_engine = engine == ENGINE_BASIC;
229 bool const haveSelection =
230 selectedLV->model()->rowCount() > 0;
232 bool const isNocite = currentStyle == NOCITE;
234 fulllistCB->setEnabled(natbib_engine && haveSelection && !isNocite);
235 forceuppercaseCB->setEnabled(natbib_engine && haveSelection && !isNocite);
236 textBeforeED->setEnabled(!basic_engine && haveSelection && !isNocite);
237 textBeforeLA->setEnabled(!basic_engine && haveSelection && !isNocite);
238 textAfterED->setEnabled(haveSelection && !isNocite);
239 textAfterLA->setEnabled(haveSelection && !isNocite);
240 citationStyleCO->setEnabled(haveSelection);
241 citationStyleLA->setEnabled(haveSelection);
245 void GuiCitation::updateStyle()
247 string const & command = params_.getCmdName();
249 // Find the style of the citekeys
250 vector<CiteStyle> const & styles = citeStyles_;
251 CitationStyle const cs = citationStyleFromString(command);
253 vector<CiteStyle>::const_iterator cit =
254 std::find(styles.begin(), styles.end(), cs.style);
256 // restore the latest natbib style
257 if (style_ >= 0 && style_ < citationStyleCO->count())
258 citationStyleCO->setCurrentIndex(style_);
260 citationStyleCO->setCurrentIndex(0);
262 if (cit != styles.end()) {
263 int const i = int(cit - styles.begin());
264 citationStyleCO->setCurrentIndex(i);
265 fulllistCB->setChecked(cs.full);
266 forceuppercaseCB->setChecked(cs.forceUpperCase);
268 fulllistCB->setChecked(false);
269 forceuppercaseCB->setChecked(false);
271 updateFormatting(cs.style);
274 // This one needs to be called whenever citationStyleCO needs
275 // to be updated---and this would be on anything that changes the
276 // selection in selectedLV, or on a general update.
277 void GuiCitation::fillStyles()
279 int const oldIndex = citationStyleCO->currentIndex();
281 citationStyleCO->clear();
283 QStringList selected_keys = selected()->stringList();
284 if (selected_keys.empty()) {
285 citationStyleCO->setEnabled(false);
286 citationStyleLA->setEnabled(false);
290 int curr = selectedLV->model()->rowCount() - 1;
294 if (!selectedLV->selectionModel()->selectedIndexes().empty())
295 curr = selectedLV->selectionModel()->selectedIndexes()[0].row();
297 QStringList sty = citationStyles(curr);
299 citationStyleCO->setEnabled(!sty.isEmpty());
300 citationStyleLA->setEnabled(!sty.isEmpty());
305 citationStyleCO->insertItems(0, sty);
307 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
308 citationStyleCO->setCurrentIndex(oldIndex);
312 void GuiCitation::fillFields()
314 fieldsCO->blockSignals(true);
315 int const oldIndex = fieldsCO->currentIndex();
317 QStringList const & fields = getFieldsAsQStringList();
318 fieldsCO->insertItem(0, qt_("All Fields"));
319 fieldsCO->insertItem(1, qt_("Keys"));
320 fieldsCO->insertItems(2, fields);
321 if (oldIndex != -1 && oldIndex < fieldsCO->count())
322 fieldsCO->setCurrentIndex(oldIndex);
323 fieldsCO->blockSignals(false);
327 void GuiCitation::fillEntries()
329 entriesCO->blockSignals(true);
330 int const oldIndex = entriesCO->currentIndex();
332 QStringList const & entries = getEntriesAsQStringList();
333 entriesCO->insertItem(0, qt_("All Entry Types"));
334 entriesCO->insertItems(1, entries);
335 if (oldIndex != -1 && oldIndex < entriesCO->count())
336 entriesCO->setCurrentIndex(oldIndex);
337 entriesCO->blockSignals(false);
341 bool GuiCitation::isSelected(const QModelIndex & idx)
343 QString const str = idx.data().toString();
344 return selected()->stringList().contains(str);
348 void GuiCitation::setButtons()
350 selectionManager->update();
351 int const srows = selectedLV->model()->rowCount();
352 applyPB->setEnabled(srows > 0);
353 okPB->setEnabled(srows > 0);
357 void GuiCitation::updateInfo(QModelIndex const & idx)
360 QString const keytxt = getKeyInfo(idx.data().toString());
361 infoML->document()->setPlainText(keytxt);
363 infoML->document()->clear();
367 void GuiCitation::findText(QString const & text, bool reset)
369 //"All Fields" and "Keys" are the first two
370 int index = fieldsCO->currentIndex() - 2;
371 vector<docstring> const & fields = availableFields();
374 if (index <= -1 || index >= int(fields.size()))
375 //either "All Fields" or "Keys" or an invalid value
376 field = from_ascii("");
378 field = fields[index];
381 bool const onlyKeys = index == -1;
383 //"All Entry Types" is first.
384 index = entriesCO->currentIndex() - 1;
385 vector<docstring> const & entries = availableEntries();
386 docstring entry_type;
387 if (index < 0 || index >= int(entries.size()))
388 entry_type = from_ascii("");
390 entry_type = entries[index];
392 bool const case_sentitive = caseCB->checkState();
393 bool const reg_exp = regexCB->checkState();
394 findKey(text, onlyKeys, field, entry_type,
395 case_sentitive, reg_exp, reset);
397 //It'd be nice to save and restore the current selection in
398 //availableLV. Currently, we get an automatic reset, since the
405 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
407 findText(findLE->text(), true);
411 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
413 findText(findLE->text(), true);
417 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
419 if (index >= 0 && index < citationStyleCO->count()) {
420 vector<CiteStyle> const & styles = citeStyles_;
421 updateFormatting(styles[index]);
426 void GuiCitation::on_findLE_textChanged(const QString & text)
428 bool const searchAsWeGo = (asTypeCB->checkState() == Qt::Checked);
429 searchPB->setDisabled(text.isEmpty() || searchAsWeGo);
430 if (!text.isEmpty()) {
432 findText(findLE->text());
435 findText(findLE->text());
439 void GuiCitation::on_searchPB_clicked()
441 findText(findLE->text(), true);
445 void GuiCitation::on_caseCB_stateChanged(int)
447 findText(findLE->text());
451 void GuiCitation::on_regexCB_stateChanged(int)
453 findText(findLE->text());
457 void GuiCitation::on_asTypeCB_stateChanged(int)
459 bool const searchAsWeGo = (asTypeCB->checkState() == Qt::Checked);
460 searchPB->setDisabled(findLE->text().isEmpty() || searchAsWeGo);
462 findText(findLE->text(), true);
466 void GuiCitation::changed()
472 void GuiCitation::apply(int const choice, bool full, bool force,
473 QString before, QString after)
475 if (cited_keys_.isEmpty())
478 vector<CiteStyle> const & styles = citeStyles_;
479 if (styles[choice] == NOCITE) {
487 s.style = styles[choice];
489 s.forceUpperCase = force;
490 string const command = citationStyleToString(s);
492 params_.setCmdName(command);
493 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
494 params_["before"] = qstring_to_ucs4(before);
495 params_["after"] = qstring_to_ucs4(after);
500 void GuiCitation::clearSelection()
503 selected_model_.setStringList(cited_keys_);
507 QString GuiCitation::textBefore()
509 return toqstr(params_["before"]);
513 QString GuiCitation::textAfter()
515 return toqstr(params_["after"]);
519 void GuiCitation::init()
521 // Make the list of all available bibliography keys
522 all_keys_ = to_qstring_list(availableKeys());
523 available_model_.setStringList(all_keys_);
525 // Ditto for the keys cited in this inset
526 QString str = toqstr(params_["key"]);
530 cited_keys_ = str.split(",");
531 selected_model_.setStringList(cited_keys_);
535 void GuiCitation::findKey(QString const & str, bool only_keys,
536 docstring field, docstring entry_type,
537 bool case_sensitive, bool reg_exp, bool reset)
539 // Used for optimisation: store last searched string.
540 static QString last_searched_string;
541 // Used to disable the above optimisation.
542 static bool last_case_sensitive;
543 static bool last_reg_exp;
544 // Reset last_searched_string in case of changed option.
545 if (last_case_sensitive != case_sensitive
546 || last_reg_exp != reg_exp) {
547 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
548 last_searched_string.clear();
550 // save option for next search.
551 last_case_sensitive = case_sensitive;
552 last_reg_exp = reg_exp;
554 Qt::CaseSensitivity qtcase = case_sensitive ?
555 Qt::CaseSensitive: Qt::CaseInsensitive;
557 // If new string (str) contains the last searched one...
559 !last_searched_string.isEmpty() &&
561 str.contains(last_searched_string, qtcase))
562 // ... then only search within already found list.
563 keys = available_model_.stringList();
565 // ... else search all keys.
567 // save searched string for next search.
568 last_searched_string = str;
572 // First, filter by entry_type, which will be faster than
573 // what follows, so we may get to do that on less.
574 vector<docstring> keyVector = to_docstring_vector(keys);
575 filterByEntryType(keyVector, entry_type);
578 result = to_qstring_list(keyVector);
580 result = to_qstring_list(searchKeys(keyVector, only_keys,
581 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
583 available_model_.setStringList(result);
587 QStringList GuiCitation::getFieldsAsQStringList()
589 return to_qstring_list(availableFields());
593 QStringList GuiCitation::getEntriesAsQStringList()
595 return to_qstring_list(availableEntries());
599 QStringList GuiCitation::citationStyles(int sel)
601 docstring const key = qstring_to_ucs4(cited_keys_[sel]);
602 return to_qstring_list(bibkeysInfo_.getCiteStrings(key, buffer()));
606 QString GuiCitation::getKeyInfo(QString const & sel)
608 return toqstr(getInfo(qstring_to_ucs4(sel)));
612 void GuiCitation::setCitedKeys()
614 cited_keys_ = selected_model_.stringList();
618 bool GuiCitation::initialiseParams(string const & data)
620 InsetCommand::string2params("citation", data, params_);
621 CiteEngine const engine = buffer().params().citeEngine();
622 bibkeysInfo_.fillWithBibKeys(&buffer());
623 citeStyles_ = citeStyles(engine);
628 void GuiCitation::clearParams()
631 bibkeysInfo_.clear();
635 vector<docstring> GuiCitation::availableKeys() const
637 return bibkeysInfo_.getKeys();
641 vector<docstring> GuiCitation::availableFields() const
643 return bibkeysInfo_.getFields();
647 vector<docstring> GuiCitation::availableEntries() const
649 return bibkeysInfo_.getEntries();
653 void GuiCitation::filterByEntryType(
654 vector<docstring> & keyVector, docstring entry_type)
656 if (entry_type.empty())
659 vector<docstring>::iterator it = keyVector.begin();
660 vector<docstring>::iterator end = keyVector.end();
662 vector<docstring> result;
663 for (; it != end; ++it) {
664 docstring const key = *it;
665 BiblioInfo::const_iterator cit = bibkeysInfo_.find(key);
666 if (cit == bibkeysInfo_.end())
668 if (cit->second.entryType() == entry_type)
669 result.push_back(key);
675 CiteEngine GuiCitation::citeEngine() const
677 return buffer().params().citeEngine();
681 docstring GuiCitation::getInfo(docstring const & key) const
683 if (bibkeysInfo_.empty())
686 return bibkeysInfo_.getInfo(key);
690 // Escape special chars.
691 // All characters are literals except: '.|*?+(){}[]^$\'
692 // These characters are literals when preceded by a "\", which is done here
693 // @todo: This function should be moved to support, and then the test in tests
694 // should be moved there as well.
695 static docstring escape_special_chars(docstring const & expr)
697 // Search for all chars '.|*?+(){}[^$]\'
698 // Note that '[' and '\' must be escaped.
699 // This is a limitation of boost::regex, but all other chars in BREs
700 // are assumed literal.
701 static const boost::regex reg("[].|*?+(){}^$\\[\\\\]");
703 // $& is a perl-like expression that expands to all
704 // of the current match
705 // The '$' must be prefixed with the escape character '\' for
706 // boost to treat it as a literal.
707 // Thus, to prefix a matched expression with '\', we use:
709 return from_utf8(boost::regex_replace(to_utf8(expr), reg, "\\\\$&"));
713 vector<docstring> GuiCitation::searchKeys(
714 vector<docstring> const & keys_to_search, bool only_keys,
715 docstring const & search_expression, docstring field,
716 bool case_sensitive, bool regex)
718 vector<docstring> foundKeys;
720 docstring expr = trim(search_expression);
725 // We must escape special chars in the search_expr so that
726 // it is treated as a simple string by boost::regex.
727 expr = escape_special_chars(expr);
729 boost::regex reg_exp;
731 reg_exp.assign(to_utf8(expr), case_sensitive ?
732 boost::regex_constants::normal : boost::regex_constants::icase);
733 } catch (boost::regex_error & e) {
734 // boost::regex throws an exception if the regular expression is not
736 LYXERR(Debug::GUI, e.what());
737 return vector<docstring>();
740 vector<docstring>::const_iterator it = keys_to_search.begin();
741 vector<docstring>::const_iterator end = keys_to_search.end();
742 for (; it != end; ++it ) {
743 BiblioInfo::const_iterator info = bibkeysInfo_.find(*it);
744 if (info == bibkeysInfo_.end())
747 BibTeXInfo const & kvm = info->second;
751 else if (field.empty())
752 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
753 else if (kvm.hasField(field))
754 data = to_utf8(kvm.getValueForField(field));
760 if (boost::regex_search(data, reg_exp))
761 foundKeys.push_back(*it);
763 catch (boost::regex_error & e) {
764 LYXERR(Debug::GUI, e.what());
765 return vector<docstring>();
772 void GuiCitation::dispatchParams()
774 std::string const lfun = InsetCommand::params2string("citation", params_);
775 dispatch(FuncRequest(getLfun(), lfun));
779 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
782 } // namespace frontend
785 #include "GuiCitation_moc.cpp"