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 "GuiSelectionManager.h"
20 #include "qt_helpers.h"
23 #include "BufferView.h"
24 #include "BiblioInfo.h"
25 #include "BufferParams.h"
26 #include "FuncRequest.h"
28 #include "insets/InsetCommand.h"
30 #include "support/debug.h"
31 #include "support/docstring.h"
32 #include "support/gettext.h"
33 #include "support/lstrings.h"
35 #include <QCloseEvent>
45 #include "support/regex.h"
52 using namespace lyx::support;
57 static vector<CiteStyle> citeStyles_;
60 template<typename String>
61 static QStringList to_qstring_list(vector<String> const & v)
65 for (size_t i = 0; i != v.size(); ++i) {
68 qlist.append(lyx::toqstr(v[i]));
74 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
76 vector<lyx::docstring> v;
77 for (int i = 0; i != qlist.size(); ++i) {
78 if (qlist[i].isEmpty())
80 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
86 GuiCitation::GuiCitation(GuiView & lv)
87 : DialogView(lv, "citation", qt_("Citation")),
88 params_(insetCode("citation"))
92 connect(citationStyleCO, SIGNAL(activated(int)),
93 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
94 connect(fulllistCB, SIGNAL(clicked()),
95 this, SLOT(changed()));
96 connect(forceuppercaseCB, SIGNAL(clicked()),
97 this, SLOT(changed()));
98 connect(textBeforeED, SIGNAL(textChanged(QString)),
99 this, SLOT(changed()));
100 connect(textAfterED, SIGNAL(textChanged(QString)),
101 this, SLOT(changed()));
102 connect(findLE, SIGNAL(returnPressed()),
103 this, SLOT(on_searchPB_clicked()));
104 connect(textBeforeED, SIGNAL(returnPressed()),
105 this, SLOT(on_okPB_clicked()));
106 connect(textAfterED, SIGNAL(returnPressed()),
107 this, SLOT(on_okPB_clicked()));
109 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
110 addPB, deletePB, upPB, downPB, &available_model_, &selected_model_);
111 connect(selectionManager, SIGNAL(selectionChanged()),
112 this, SLOT(setCitedKeys()));
113 connect(selectionManager, SIGNAL(updateHook()),
114 this, SLOT(updateControls()));
115 connect(selectionManager, SIGNAL(okHook()),
116 this, SLOT(on_okPB_clicked()));
118 setFocusProxy(availableLV);
120 // FIXME: the sizeHint() for this is _way_ too high
121 infoML->setFixedHeight(60);
125 GuiCitation::~GuiCitation()
127 delete selectionManager;
131 void GuiCitation::closeEvent(QCloseEvent * e)
134 DialogView::closeEvent(e);
138 void GuiCitation::applyView()
140 int const choice = max(0, citationStyleCO->currentIndex());
142 bool const full = fulllistCB->isChecked();
143 bool const force = forceuppercaseCB->isChecked();
145 QString const before = textBeforeED->text();
146 QString const after = textAfterED->text();
148 apply(choice, full, force, before, after);
152 void GuiCitation::showEvent(QShowEvent * e)
155 availableLV->setFocus();
156 DialogView::showEvent(e);
160 void GuiCitation::on_okPB_clicked()
168 void GuiCitation::on_cancelPB_clicked()
175 void GuiCitation::on_applyPB_clicked()
181 void GuiCitation::on_restorePB_clicked()
187 void GuiCitation::updateControls()
189 BiblioInfo const & bi = bibInfo();
194 // The main point of separating this out is that the fill*() methods
195 // called in update() do not need to be called for INTERNAL updates,
196 // such as when addPB is pressed, as the list of fields, entries, etc,
197 // will not have changed. At the moment, however, the division between
198 // fillStyles() and updateStyle() doesn't lend itself to dividing the
199 // two methods, though they should be divisible. That is, we should
200 // not have to call fillStyles() every time through here.
201 void GuiCitation::updateControls(BiblioInfo const & bi)
203 QModelIndex idx = selectionManager->getSelectedIndex();
207 textBeforeED->setText(toqstr(params_["before"]));
208 textAfterED->setText(toqstr(params_["after"]));
214 void GuiCitation::updateFormatting(CiteStyle currentStyle)
216 CiteEngine const engine = citeEngine();
217 bool const natbib_engine =
218 engine == ENGINE_NATBIB_AUTHORYEAR ||
219 engine == ENGINE_NATBIB_NUMERICAL;
220 bool const basic_engine = engine == ENGINE_BASIC;
222 bool const haveSelection =
223 selectedLV->model()->rowCount() > 0;
225 bool const isNocite = currentStyle == NOCITE;
227 bool const isCiteyear =
228 currentStyle == CITEYEAR ||
229 currentStyle == CITEYEARPAR;
231 fulllistCB->setEnabled(natbib_engine && haveSelection && !isNocite
233 forceuppercaseCB->setEnabled(natbib_engine && haveSelection
234 && !isNocite && !isCiteyear);
235 textBeforeED->setEnabled(!basic_engine && haveSelection && !isNocite);
236 textBeforeLA->setEnabled(!basic_engine && haveSelection && !isNocite);
237 textAfterED->setEnabled(haveSelection && !isNocite);
238 textAfterLA->setEnabled(haveSelection && !isNocite);
239 citationStyleCO->setEnabled(haveSelection);
240 citationStyleLA->setEnabled(haveSelection);
244 void GuiCitation::updateStyle()
246 string const & command = params_.getCmdName();
248 // Find the style of the citekeys
249 vector<CiteStyle> const & styles = citeStyles_;
250 CitationStyle const cs = citationStyleFromString(command);
252 vector<CiteStyle>::const_iterator cit =
253 std::find(styles.begin(), styles.end(), cs.style);
255 if (cit != styles.end()) {
256 fulllistCB->setChecked(cs.full);
257 forceuppercaseCB->setChecked(cs.forceUpperCase);
259 // restore the last used natbib style
260 if (style_ >= 0 && style_ < citationStyleCO->count()) {
261 // the necessary update will be performed later
262 citationStyleCO->blockSignals(true);
263 citationStyleCO->setCurrentIndex(style_);
264 citationStyleCO->blockSignals(false);
266 fulllistCB->setChecked(false);
267 forceuppercaseCB->setChecked(false);
269 updateFormatting(cs.style);
273 // This one needs to be called whenever citationStyleCO needs
274 // to be updated---and this would be on anything that changes the
275 // selection in selectedLV, or on a general update.
276 void GuiCitation::fillStyles(BiblioInfo const & bi)
278 QStringList selected_keys = selected_model_.stringList();
279 int curr = selectedLV->model()->rowCount() - 1;
281 if (curr < 0 || selected_keys.empty()) {
282 citationStyleCO->clear();
283 citationStyleCO->setEnabled(false);
284 citationStyleLA->setEnabled(false);
288 if (!selectedLV->selectionModel()->selectedIndexes().empty())
289 curr = selectedLV->selectionModel()->selectedIndexes()[0].row();
291 QStringList sty = citationStyles(bi, curr);
295 citationStyleCO->setEnabled(false);
296 citationStyleLA->setEnabled(false);
297 citationStyleCO->clear();
301 citationStyleCO->blockSignals(true);
304 int const oldIndex = citationStyleCO->currentIndex();
305 citationStyleCO->clear();
306 citationStyleCO->insertItems(0, sty);
307 citationStyleCO->setEnabled(true);
308 citationStyleLA->setEnabled(true);
310 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
311 citationStyleCO->setCurrentIndex(oldIndex);
313 citationStyleCO->blockSignals(false);
317 void GuiCitation::fillFields(BiblioInfo const & bi)
319 fieldsCO->blockSignals(true);
320 int const oldIndex = fieldsCO->currentIndex();
322 QStringList const fields = to_qstring_list(bi.getFields());
323 fieldsCO->insertItem(0, qt_("All fields"));
324 fieldsCO->insertItem(1, qt_("Keys"));
325 fieldsCO->insertItems(2, fields);
326 if (oldIndex != -1 && oldIndex < fieldsCO->count())
327 fieldsCO->setCurrentIndex(oldIndex);
328 fieldsCO->blockSignals(false);
332 void GuiCitation::fillEntries(BiblioInfo const & bi)
334 entriesCO->blockSignals(true);
335 int const oldIndex = entriesCO->currentIndex();
337 QStringList const entries = to_qstring_list(bi.getEntries());
338 entriesCO->insertItem(0, qt_("All entry types"));
339 entriesCO->insertItems(1, entries);
340 if (oldIndex != -1 && oldIndex < entriesCO->count())
341 entriesCO->setCurrentIndex(oldIndex);
342 entriesCO->blockSignals(false);
346 bool GuiCitation::isSelected(QModelIndex const & idx)
348 QString const str = idx.data().toString();
349 return selected_model_.stringList().contains(str);
353 void GuiCitation::setButtons()
355 selectionManager->update();
356 int const srows = selectedLV->model()->rowCount();
357 applyPB->setEnabled(srows > 0);
358 okPB->setEnabled(srows > 0);
362 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
364 if (!idx.isValid() || bi.empty()) {
365 infoML->document()->clear();
369 QString const keytxt = toqstr(
370 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), true));
371 infoML->document()->setHtml(keytxt);
375 void GuiCitation::findText(QString const & text, bool reset)
377 //"All Fields" and "Keys" are the first two
378 int index = fieldsCO->currentIndex() - 2;
379 BiblioInfo const & bi = bibInfo();
380 vector<docstring> const & fields = bi.getFields();
383 if (index <= -1 || index >= int(fields.size()))
384 //either "All Fields" or "Keys" or an invalid value
385 field = from_ascii("");
387 field = fields[index];
390 bool const onlyKeys = index == -1;
392 //"All Entry Types" is first.
393 index = entriesCO->currentIndex() - 1;
394 vector<docstring> const & entries = bi.getEntries();
395 docstring entry_type;
396 if (index < 0 || index >= int(entries.size()))
397 entry_type = from_ascii("");
399 entry_type = entries[index];
401 bool const case_sentitive = caseCB->checkState();
402 bool const reg_exp = regexCB->checkState();
403 findKey(bi, text, onlyKeys, field, entry_type,
404 case_sentitive, reg_exp, reset);
406 //It'd be nice to save and restore the current selection in
407 //availableLV. Currently, we get an automatic reset, since the
414 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
416 findText(findLE->text(), true);
420 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
422 findText(findLE->text(), true);
426 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
428 if (index >= 0 && index < citationStyleCO->count()) {
429 vector<CiteStyle> const & styles = citeStyles_;
430 updateFormatting(styles[index]);
435 void GuiCitation::on_findLE_textChanged(const QString & text)
437 bool const searchAsWeGo = (asTypeCB->checkState() == Qt::Checked);
438 searchPB->setDisabled(text.isEmpty() || searchAsWeGo);
439 if (!text.isEmpty()) {
441 findText(findLE->text());
444 findText(findLE->text());
448 void GuiCitation::on_searchPB_clicked()
450 findText(findLE->text(), true);
454 void GuiCitation::on_caseCB_stateChanged(int)
456 findText(findLE->text());
460 void GuiCitation::on_regexCB_stateChanged(int)
462 findText(findLE->text());
466 void GuiCitation::on_asTypeCB_stateChanged(int)
468 bool const searchAsWeGo = (asTypeCB->checkState() == Qt::Checked);
469 searchPB->setDisabled(findLE->text().isEmpty() || searchAsWeGo);
471 findText(findLE->text(), true);
475 void GuiCitation::changed()
481 void GuiCitation::apply(int const choice, bool full, bool force,
482 QString before, QString after)
484 if (cited_keys_.isEmpty())
487 vector<CiteStyle> const & styles = citeStyles_;
488 if (styles[choice] == NOCITE) {
496 s.style = styles[choice];
498 s.forceUpperCase = force;
499 string const command = citationStyleToString(s);
501 params_.setCmdName(command);
502 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
503 params_["before"] = qstring_to_ucs4(before);
504 params_["after"] = qstring_to_ucs4(after);
509 void GuiCitation::clearSelection()
512 selected_model_.setStringList(cited_keys_);
516 void GuiCitation::init()
518 // Make the list of all available bibliography keys
519 BiblioInfo const & bi = bibInfo();
520 all_keys_ = to_qstring_list(bi.getKeys());
521 available_model_.setStringList(all_keys_);
523 // Ditto for the keys cited in this inset
524 QString str = toqstr(params_["key"]);
528 cited_keys_ = str.split(",");
529 selected_model_.setStringList(cited_keys_);
530 if (selected_model_.rowCount()) {
531 selectedLV->blockSignals(true);
532 selectedLV->setFocus();
533 QModelIndex idx = selected_model_.index(0, 0);
534 selectedLV->selectionModel()->select(idx,
535 QItemSelectionModel::ClearAndSelect);
536 selectedLV->blockSignals(false);
538 // set the style combo appropriately
539 string const & command = params_.getCmdName();
540 vector<CiteStyle> const & styles = citeStyles_;
541 CitationStyle const cs = citationStyleFromString(command);
543 vector<CiteStyle>::const_iterator cit =
544 std::find(styles.begin(), styles.end(), cs.style);
545 if (cit != styles.end()) {
546 int const i = int(cit - styles.begin());
547 // the necessary update will be performed later
548 citationStyleCO->blockSignals(true);
549 citationStyleCO->setCurrentIndex(i);
550 citationStyleCO->blockSignals(false);
553 availableLV->setFocus();
560 void GuiCitation::findKey(BiblioInfo const & bi,
561 QString const & str, bool only_keys,
562 docstring field, docstring entry_type,
563 bool case_sensitive, bool reg_exp, bool reset)
565 // Used for optimisation: store last searched string.
566 static QString last_searched_string;
567 // Used to disable the above optimisation.
568 static bool last_case_sensitive;
569 static bool last_reg_exp;
570 // Reset last_searched_string in case of changed option.
571 if (last_case_sensitive != case_sensitive
572 || last_reg_exp != reg_exp) {
573 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
574 last_searched_string.clear();
576 // save option for next search.
577 last_case_sensitive = case_sensitive;
578 last_reg_exp = reg_exp;
580 Qt::CaseSensitivity qtcase = case_sensitive ?
581 Qt::CaseSensitive: Qt::CaseInsensitive;
583 // If new string (str) contains the last searched one...
585 !last_searched_string.isEmpty() &&
587 str.contains(last_searched_string, qtcase))
588 // ... then only search within already found list.
589 keys = available_model_.stringList();
591 // ... else search all keys.
593 // save searched string for next search.
594 last_searched_string = str;
598 // First, filter by entry_type, which will be faster than
599 // what follows, so we may get to do that on less.
600 vector<docstring> keyVector = to_docstring_vector(keys);
601 filterByEntryType(bi, keyVector, entry_type);
604 result = to_qstring_list(keyVector);
606 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
607 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
609 available_model_.setStringList(result);
613 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, int sel)
615 docstring const key = qstring_to_ucs4(cited_keys_[sel]);
616 return to_qstring_list(bi.getCiteStrings(key, documentBuffer()));
620 void GuiCitation::setCitedKeys()
622 cited_keys_ = selected_model_.stringList();
626 bool GuiCitation::initialiseParams(string const & data)
628 InsetCommand::string2params(data, params_);
629 CiteEngine const engine = citeEngine();
630 citeStyles_ = citeStyles(engine);
636 void GuiCitation::clearParams()
642 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
643 vector<docstring> & keyVector, docstring entry_type)
645 if (entry_type.empty())
648 vector<docstring>::iterator it = keyVector.begin();
649 vector<docstring>::iterator end = keyVector.end();
651 vector<docstring> result;
652 for (; it != end; ++it) {
653 docstring const key = *it;
654 BiblioInfo::const_iterator cit = bi.find(key);
657 if (cit->second.entryType() == entry_type)
658 result.push_back(key);
664 CiteEngine GuiCitation::citeEngine() const
666 return documentBuffer().params().citeEngine();
670 // Escape special chars.
671 // All characters are literals except: '.|*?+(){}[]^$\'
672 // These characters are literals when preceded by a "\", which is done here
673 // @todo: This function should be moved to support, and then the test in tests
674 // should be moved there as well.
675 static docstring escape_special_chars(docstring const & expr)
677 // Search for all chars '.|*?+(){}[^$]\'
678 // Note that '[' and '\' must be escaped.
679 // This is a limitation of lyx::regex, but all other chars in BREs
680 // are assumed literal.
681 static const lyx::regex reg("[].|*?+(){}^$\\[\\\\]");
683 // $& is a perl-like expression that expands to all
684 // of the current match
685 // The '$' must be prefixed with the escape character '\' for
686 // boost to treat it as a literal.
687 // Thus, to prefix a matched expression with '\', we use:
689 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
693 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
694 vector<docstring> const & keys_to_search, bool only_keys,
695 docstring const & search_expression, docstring field,
696 bool case_sensitive, bool regex)
698 vector<docstring> foundKeys;
700 docstring expr = trim(search_expression);
705 // We must escape special chars in the search_expr so that
706 // it is treated as a simple string by lyx::regex.
707 expr = escape_special_chars(expr);
711 reg_exp.assign(to_utf8(expr), case_sensitive ?
712 lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
713 } catch (lyx::regex_error & e) {
714 // lyx::regex throws an exception if the regular expression is not
716 LYXERR(Debug::GUI, e.what());
717 return vector<docstring>();
720 vector<docstring>::const_iterator it = keys_to_search.begin();
721 vector<docstring>::const_iterator end = keys_to_search.end();
722 for (; it != end; ++it ) {
723 BiblioInfo::const_iterator info = bi.find(*it);
724 if (info == bi.end())
727 BibTeXInfo const & kvm = info->second;
731 else if (field.empty())
732 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
734 data = to_utf8(kvm[field]);
740 if (lyx::regex_search(data, reg_exp))
741 foundKeys.push_back(*it);
743 catch (lyx::regex_error & e) {
744 LYXERR(Debug::GUI, e.what());
745 return vector<docstring>();
752 void GuiCitation::dispatchParams()
754 std::string const lfun = InsetCommand::params2string(params_);
755 dispatch(FuncRequest(getLfun(), lfun));
759 BiblioInfo const & GuiCitation::bibInfo() const
761 Buffer const & buf = documentBuffer();
762 buf.reloadBibInfoCache();
763 return buf.masterBibInfo();
767 void GuiCitation::saveSession() const
769 Dialog::saveSession();
772 sessionKey() + "/regex", regexCB->isChecked());
774 sessionKey() + "/casesensitive", caseCB->isChecked());
776 sessionKey() + "/autofind", asTypeCB->isChecked());
780 void GuiCitation::restoreSession()
782 Dialog::restoreSession();
785 settings.value(sessionKey() + "/regex").toBool());
787 settings.value(sessionKey() + "/casesensitive").toBool());
788 asTypeCB->setChecked(
789 settings.value(sessionKey() + "/autofind").toBool());
793 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
796 } // namespace frontend
799 #include "moc_GuiCitation.cpp"