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 "GuiSelectionManager.h"
19 #include "qt_helpers.h"
22 #include "BiblioInfo.h"
23 #include "BufferParams.h"
24 #include "FuncRequest.h"
26 #include "insets/InsetCommand.h"
28 #include "support/debug.h"
29 #include "support/docstring.h"
30 #include "support/gettext.h"
31 #include "support/lstrings.h"
33 #include <QCloseEvent>
41 #include <boost/regex.hpp>
48 using namespace lyx::support;
53 static vector<CiteStyle> citeStyles_;
56 template<typename String>
57 static QStringList to_qstring_list(vector<String> const & v)
61 for (size_t i = 0; i != v.size(); ++i) {
64 qlist.append(lyx::toqstr(v[i]));
70 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
72 vector<lyx::docstring> v;
73 for (int i = 0; i != qlist.size(); ++i) {
74 if (qlist[i].isEmpty())
76 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
82 GuiCitation::GuiCitation(GuiView & lv)
83 : DialogView(lv, "citation", qt_("Citation")),
84 params_(insetCode("citation"))
88 connect(citationStyleCO, SIGNAL(activated(int)),
89 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
90 connect(fulllistCB, SIGNAL(clicked()),
91 this, SLOT(changed()));
92 connect(forceuppercaseCB, SIGNAL(clicked()),
93 this, SLOT(changed()));
94 connect(textBeforeED, SIGNAL(textChanged(QString)),
95 this, SLOT(changed()));
96 connect(textAfterED, SIGNAL(textChanged(QString)),
97 this, SLOT(changed()));
98 connect(findLE, SIGNAL(returnPressed()),
99 this, SLOT(on_searchPB_clicked()));
100 connect(textBeforeED, SIGNAL(returnPressed()),
101 this, SLOT(on_okPB_clicked()));
102 connect(textAfterED, SIGNAL(returnPressed()),
103 this, SLOT(on_okPB_clicked()));
105 connect(this, SIGNAL(rejected()), this, SLOT(cleanUp()));
107 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
108 addPB, deletePB, upPB, downPB, &available_model_, &selected_model_);
109 connect(selectionManager, SIGNAL(selectionChanged()),
110 this, SLOT(setCitedKeys()));
111 connect(selectionManager, SIGNAL(updateHook()),
112 this, SLOT(updateControls()));
113 connect(selectionManager, SIGNAL(okHook()),
114 this, SLOT(on_okPB_clicked()));
116 // FIXME: the sizeHint() for this is _way_ too high
117 infoML->setFixedHeight(60);
121 GuiCitation::~GuiCitation()
123 delete selectionManager;
127 void GuiCitation::cleanUp()
135 void GuiCitation::closeEvent(QCloseEvent * e)
143 void GuiCitation::applyView()
145 int const choice = max(0, citationStyleCO->currentIndex());
147 bool const full = fulllistCB->isChecked();
148 bool const force = forceuppercaseCB->isChecked();
150 QString const before = textBeforeED->text();
151 QString const after = textAfterED->text();
153 apply(choice, full, force, before, after);
157 void GuiCitation::showEvent(QShowEvent * e)
160 availableLV->setFocus();
161 DialogView::showEvent(e);
165 void GuiCitation::on_okPB_clicked()
173 void GuiCitation::on_cancelPB_clicked()
180 void GuiCitation::on_applyPB_clicked()
186 void GuiCitation::on_restorePB_clicked()
192 // The main point of separating this out is that the fill*() methods
193 // called in update() do not need to be called for INTERNAL updates,
194 // such as when addPB is pressed, as the list of fields, entries, etc,
195 // will not have changed. At the moment, however, the division between
196 // fillStyles() and updateStyle() doesn't lend itself to dividing the
197 // two methods, though they should be divisible.
198 void GuiCitation::updateControls()
200 if (selectionManager->selectedFocused()) {
201 if (selectedLV->selectionModel()->selectedIndexes().isEmpty())
202 updateInfo(availableLV->currentIndex());
204 updateInfo(selectedLV->currentIndex());
206 if (availableLV->selectionModel()->selectedIndexes().isEmpty())
207 updateInfo(QModelIndex());
209 updateInfo(availableLV->currentIndex());
213 textBeforeED->setText(toqstr(params_["before"]));
214 textAfterED->setText(toqstr(params_["after"]));
220 void GuiCitation::updateFormatting(CiteStyle currentStyle)
222 CiteEngine const engine = citeEngine();
223 bool const natbib_engine =
224 engine == ENGINE_NATBIB_AUTHORYEAR ||
225 engine == ENGINE_NATBIB_NUMERICAL;
226 bool const basic_engine = engine == ENGINE_BASIC;
228 bool const haveSelection =
229 selectedLV->model()->rowCount() > 0;
231 bool const isNocite = currentStyle == NOCITE;
233 fulllistCB->setEnabled(natbib_engine && haveSelection && !isNocite);
234 forceuppercaseCB->setEnabled(natbib_engine && haveSelection && !isNocite);
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 // restore the latest natbib style
256 if (style_ >= 0 && style_ < citationStyleCO->count())
257 citationStyleCO->setCurrentIndex(style_);
259 citationStyleCO->setCurrentIndex(0);
261 if (cit != styles.end()) {
262 int const i = int(cit - styles.begin());
263 citationStyleCO->setCurrentIndex(i);
264 fulllistCB->setChecked(cs.full);
265 forceuppercaseCB->setChecked(cs.forceUpperCase);
267 fulllistCB->setChecked(false);
268 forceuppercaseCB->setChecked(false);
270 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()
278 int const oldIndex = citationStyleCO->currentIndex();
280 citationStyleCO->clear();
282 QStringList selected_keys = selected_model_.stringList();
283 if (selected_keys.empty()) {
284 citationStyleCO->setEnabled(false);
285 citationStyleLA->setEnabled(false);
289 int curr = selectedLV->model()->rowCount() - 1;
293 if (!selectedLV->selectionModel()->selectedIndexes().empty())
294 curr = selectedLV->selectionModel()->selectedIndexes()[0].row();
296 QStringList sty = citationStyles(curr);
298 citationStyleCO->setEnabled(!sty.isEmpty());
299 citationStyleLA->setEnabled(!sty.isEmpty());
304 citationStyleCO->insertItems(0, sty);
306 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
307 citationStyleCO->setCurrentIndex(oldIndex);
311 void GuiCitation::fillFields()
313 fieldsCO->blockSignals(true);
314 int const oldIndex = fieldsCO->currentIndex();
316 QStringList const fields = to_qstring_list(bibInfo().getFields());
317 fieldsCO->insertItem(0, qt_("All Fields"));
318 fieldsCO->insertItem(1, qt_("Keys"));
319 fieldsCO->insertItems(2, fields);
320 if (oldIndex != -1 && oldIndex < fieldsCO->count())
321 fieldsCO->setCurrentIndex(oldIndex);
322 fieldsCO->blockSignals(false);
326 void GuiCitation::fillEntries()
328 entriesCO->blockSignals(true);
329 int const oldIndex = entriesCO->currentIndex();
331 QStringList const entries = to_qstring_list(bibInfo().getEntries());
332 entriesCO->insertItem(0, qt_("All Entry Types"));
333 entriesCO->insertItems(1, entries);
334 if (oldIndex != -1 && oldIndex < entriesCO->count())
335 entriesCO->setCurrentIndex(oldIndex);
336 entriesCO->blockSignals(false);
340 bool GuiCitation::isSelected(const QModelIndex & idx)
342 QString const str = idx.data().toString();
343 return selected_model_.stringList().contains(str);
347 void GuiCitation::setButtons()
349 selectionManager->update();
350 int const srows = selectedLV->model()->rowCount();
351 applyPB->setEnabled(srows > 0);
352 okPB->setEnabled(srows > 0);
356 void GuiCitation::updateInfo(QModelIndex const & idx)
358 if (!idx.isValid() || bibInfo().empty()) {
359 infoML->document()->clear();
363 QString const keytxt = toqstr(
364 bibInfo().getInfo(qstring_to_ucs4(idx.data().toString())));
365 infoML->document()->setPlainText(keytxt);
369 void GuiCitation::findText(QString const & text, bool reset)
371 //"All Fields" and "Keys" are the first two
372 int index = fieldsCO->currentIndex() - 2;
373 vector<docstring> const & fields = bibInfo().getFields();
376 if (index <= -1 || index >= int(fields.size()))
377 //either "All Fields" or "Keys" or an invalid value
378 field = from_ascii("");
380 field = fields[index];
383 bool const onlyKeys = index == -1;
385 //"All Entry Types" is first.
386 index = entriesCO->currentIndex() - 1;
387 vector<docstring> const & entries = bibInfo().getEntries();
388 docstring entry_type;
389 if (index < 0 || index >= int(entries.size()))
390 entry_type = from_ascii("");
392 entry_type = entries[index];
394 bool const case_sentitive = caseCB->checkState();
395 bool const reg_exp = regexCB->checkState();
396 findKey(text, onlyKeys, field, entry_type,
397 case_sentitive, reg_exp, reset);
399 //It'd be nice to save and restore the current selection in
400 //availableLV. Currently, we get an automatic reset, since the
407 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
409 findText(findLE->text(), true);
413 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
415 findText(findLE->text(), true);
419 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
421 if (index >= 0 && index < citationStyleCO->count()) {
422 vector<CiteStyle> const & styles = citeStyles_;
423 updateFormatting(styles[index]);
428 void GuiCitation::on_findLE_textChanged(const QString & text)
430 bool const searchAsWeGo = (asTypeCB->checkState() == Qt::Checked);
431 searchPB->setDisabled(text.isEmpty() || searchAsWeGo);
432 if (!text.isEmpty()) {
434 findText(findLE->text());
437 findText(findLE->text());
441 void GuiCitation::on_searchPB_clicked()
443 findText(findLE->text(), true);
447 void GuiCitation::on_caseCB_stateChanged(int)
449 findText(findLE->text());
453 void GuiCitation::on_regexCB_stateChanged(int)
455 findText(findLE->text());
459 void GuiCitation::on_asTypeCB_stateChanged(int)
461 bool const searchAsWeGo = (asTypeCB->checkState() == Qt::Checked);
462 searchPB->setDisabled(findLE->text().isEmpty() || searchAsWeGo);
464 findText(findLE->text(), true);
468 void GuiCitation::changed()
474 void GuiCitation::apply(int const choice, bool full, bool force,
475 QString before, QString after)
477 if (cited_keys_.isEmpty())
480 vector<CiteStyle> const & styles = citeStyles_;
481 if (styles[choice] == NOCITE) {
489 s.style = styles[choice];
491 s.forceUpperCase = force;
492 string const command = citationStyleToString(s);
494 params_.setCmdName(command);
495 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
496 params_["before"] = qstring_to_ucs4(before);
497 params_["after"] = qstring_to_ucs4(after);
502 void GuiCitation::clearSelection()
505 selected_model_.setStringList(cited_keys_);
509 void GuiCitation::init()
511 // Make the list of all available bibliography keys
512 all_keys_ = to_qstring_list(bibInfo().getKeys());
513 available_model_.setStringList(all_keys_);
515 // Ditto for the keys cited in this inset
516 QString str = toqstr(params_["key"]);
520 cited_keys_ = str.split(",");
521 selected_model_.setStringList(cited_keys_);
529 void GuiCitation::findKey(QString const & str, bool only_keys,
530 docstring field, docstring entry_type,
531 bool case_sensitive, bool reg_exp, bool reset)
533 // Used for optimisation: store last searched string.
534 static QString last_searched_string;
535 // Used to disable the above optimisation.
536 static bool last_case_sensitive;
537 static bool last_reg_exp;
538 // Reset last_searched_string in case of changed option.
539 if (last_case_sensitive != case_sensitive
540 || last_reg_exp != reg_exp) {
541 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
542 last_searched_string.clear();
544 // save option for next search.
545 last_case_sensitive = case_sensitive;
546 last_reg_exp = reg_exp;
548 Qt::CaseSensitivity qtcase = case_sensitive ?
549 Qt::CaseSensitive: Qt::CaseInsensitive;
551 // If new string (str) contains the last searched one...
553 !last_searched_string.isEmpty() &&
555 str.contains(last_searched_string, qtcase))
556 // ... then only search within already found list.
557 keys = available_model_.stringList();
559 // ... else search all keys.
561 // save searched string for next search.
562 last_searched_string = str;
566 // First, filter by entry_type, which will be faster than
567 // what follows, so we may get to do that on less.
568 vector<docstring> keyVector = to_docstring_vector(keys);
569 filterByEntryType(keyVector, entry_type);
572 result = to_qstring_list(keyVector);
574 result = to_qstring_list(searchKeys(keyVector, only_keys,
575 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
577 available_model_.setStringList(result);
581 QStringList GuiCitation::citationStyles(int sel)
583 docstring const key = qstring_to_ucs4(cited_keys_[sel]);
584 return to_qstring_list(bibInfo().getCiteStrings(key, buffer()));
588 void GuiCitation::setCitedKeys()
590 cited_keys_ = selected_model_.stringList();
594 bool GuiCitation::initialiseParams(string const & data)
596 InsetCommand::string2params("citation", data, params_);
597 CiteEngine const engine = buffer().params().citeEngine();
598 citeStyles_ = citeStyles(engine);
604 void GuiCitation::clearParams()
610 void GuiCitation::filterByEntryType(
611 vector<docstring> & keyVector, docstring entry_type)
613 if (entry_type.empty())
616 vector<docstring>::iterator it = keyVector.begin();
617 vector<docstring>::iterator end = keyVector.end();
619 vector<docstring> result;
620 for (; it != end; ++it) {
621 docstring const key = *it;
622 BiblioInfo::const_iterator cit = bibInfo().find(key);
623 if (cit == bibInfo().end())
625 if (cit->second.entryType() == entry_type)
626 result.push_back(key);
632 CiteEngine GuiCitation::citeEngine() const
634 return buffer().params().citeEngine();
638 // Escape special chars.
639 // All characters are literals except: '.|*?+(){}[]^$\'
640 // These characters are literals when preceded by a "\", which is done here
641 // @todo: This function should be moved to support, and then the test in tests
642 // should be moved there as well.
643 static docstring escape_special_chars(docstring const & expr)
645 // Search for all chars '.|*?+(){}[^$]\'
646 // Note that '[' and '\' must be escaped.
647 // This is a limitation of boost::regex, but all other chars in BREs
648 // are assumed literal.
649 static const boost::regex reg("[].|*?+(){}^$\\[\\\\]");
651 // $& is a perl-like expression that expands to all
652 // of the current match
653 // The '$' must be prefixed with the escape character '\' for
654 // boost to treat it as a literal.
655 // Thus, to prefix a matched expression with '\', we use:
657 return from_utf8(boost::regex_replace(to_utf8(expr), reg, "\\\\$&"));
661 vector<docstring> GuiCitation::searchKeys(
662 vector<docstring> const & keys_to_search, bool only_keys,
663 docstring const & search_expression, docstring field,
664 bool case_sensitive, bool regex)
666 vector<docstring> foundKeys;
668 docstring expr = trim(search_expression);
673 // We must escape special chars in the search_expr so that
674 // it is treated as a simple string by boost::regex.
675 expr = escape_special_chars(expr);
677 boost::regex reg_exp;
679 reg_exp.assign(to_utf8(expr), case_sensitive ?
680 boost::regex_constants::normal : boost::regex_constants::icase);
681 } catch (boost::regex_error & e) {
682 // boost::regex throws an exception if the regular expression is not
684 LYXERR(Debug::GUI, e.what());
685 return vector<docstring>();
688 vector<docstring>::const_iterator it = keys_to_search.begin();
689 vector<docstring>::const_iterator end = keys_to_search.end();
690 for (; it != end; ++it ) {
691 BiblioInfo::const_iterator info = bibInfo().find(*it);
692 if (info == bibInfo().end())
695 BibTeXInfo const & kvm = info->second;
699 else if (field.empty())
700 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
701 else if (kvm.hasField(field))
702 data = to_utf8(kvm.getValueForField(field));
708 if (boost::regex_search(data, reg_exp))
709 foundKeys.push_back(*it);
711 catch (boost::regex_error & e) {
712 LYXERR(Debug::GUI, e.what());
713 return vector<docstring>();
720 void GuiCitation::dispatchParams()
722 std::string const lfun = InsetCommand::params2string("citation", params_);
723 dispatch(FuncRequest(getLfun(), lfun));
727 BiblioInfo const & GuiCitation::bibInfo() const
729 return buffer().masterBibInfo();
733 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
736 } // namespace frontend
739 #include "GuiCitation_moc.cpp"