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 "BiblioInfo.h"
24 #include "BufferParams.h"
25 #include "FuncRequest.h"
27 #include "insets/InsetCommand.h"
29 #include "support/debug.h"
30 #include "support/docstring.h"
31 #include "support/gettext.h"
32 #include "support/lstrings.h"
34 #include <QCloseEvent>
44 #include <boost/regex.hpp>
51 using namespace lyx::support;
56 static vector<CiteStyle> citeStyles_;
59 template<typename String>
60 static QStringList to_qstring_list(vector<String> const & v)
64 for (size_t i = 0; i != v.size(); ++i) {
67 qlist.append(lyx::toqstr(v[i]));
73 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
75 vector<lyx::docstring> v;
76 for (int i = 0; i != qlist.size(); ++i) {
77 if (qlist[i].isEmpty())
79 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
85 GuiCitation::GuiCitation(GuiView & lv)
86 : DialogView(lv, "citation", qt_("Citation")),
87 params_(insetCode("citation"))
91 connect(citationStyleCO, SIGNAL(activated(int)),
92 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
93 connect(fulllistCB, SIGNAL(clicked()),
94 this, SLOT(changed()));
95 connect(forceuppercaseCB, SIGNAL(clicked()),
96 this, SLOT(changed()));
97 connect(textBeforeED, SIGNAL(textChanged(QString)),
98 this, SLOT(changed()));
99 connect(textAfterED, SIGNAL(textChanged(QString)),
100 this, SLOT(changed()));
101 connect(findLE, SIGNAL(returnPressed()),
102 this, SLOT(on_searchPB_clicked()));
103 connect(textBeforeED, SIGNAL(returnPressed()),
104 this, SLOT(on_okPB_clicked()));
105 connect(textAfterED, SIGNAL(returnPressed()),
106 this, SLOT(on_okPB_clicked()));
108 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
109 addPB, deletePB, upPB, downPB, &available_model_, &selected_model_);
110 connect(selectionManager, SIGNAL(selectionChanged()),
111 this, SLOT(setCitedKeys()));
112 connect(selectionManager, SIGNAL(updateHook()),
113 this, SLOT(updateControls()));
114 connect(selectionManager, SIGNAL(okHook()),
115 this, SLOT(on_okPB_clicked()));
117 setFocusProxy(availableLV);
119 // FIXME: the sizeHint() for this is _way_ too high
120 infoML->setFixedHeight(60);
124 GuiCitation::~GuiCitation()
126 delete selectionManager;
130 void GuiCitation::closeEvent(QCloseEvent * e)
133 DialogView::closeEvent(e);
137 void GuiCitation::applyView()
139 int const choice = max(0, citationStyleCO->currentIndex());
141 bool const full = fulllistCB->isChecked();
142 bool const force = forceuppercaseCB->isChecked();
144 QString const before = textBeforeED->text();
145 QString const after = textAfterED->text();
147 apply(choice, full, force, before, after);
151 void GuiCitation::showEvent(QShowEvent * e)
154 availableLV->setFocus();
155 DialogView::showEvent(e);
159 void GuiCitation::on_okPB_clicked()
167 void GuiCitation::on_cancelPB_clicked()
174 void GuiCitation::on_applyPB_clicked()
180 void GuiCitation::on_restorePB_clicked()
186 void GuiCitation::updateControls()
188 BiblioInfo const & bi = bibInfo();
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::updateControls(BiblioInfo const & bi)
201 if (selectionManager->selectedFocused()) {
202 if (selectedLV->selectionModel()->selectedIndexes().isEmpty())
203 updateInfo(bi, availableLV->currentIndex());
205 updateInfo(bi, selectedLV->currentIndex());
207 if (availableLV->selectionModel()->selectedIndexes().isEmpty())
208 updateInfo(bi, QModelIndex());
210 updateInfo(bi, availableLV->currentIndex());
214 textBeforeED->setText(toqstr(params_["before"]));
215 textAfterED->setText(toqstr(params_["after"]));
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 bool const isCiteyear =
235 currentStyle == CITEYEAR ||
236 currentStyle == CITEYEARPAR;
238 fulllistCB->setEnabled(natbib_engine && haveSelection && !isNocite
240 forceuppercaseCB->setEnabled(natbib_engine && haveSelection
241 && !isNocite && !isCiteyear);
242 textBeforeED->setEnabled(!basic_engine && haveSelection && !isNocite);
243 textBeforeLA->setEnabled(!basic_engine && haveSelection && !isNocite);
244 textAfterED->setEnabled(haveSelection && !isNocite);
245 textAfterLA->setEnabled(haveSelection && !isNocite);
246 citationStyleCO->setEnabled(haveSelection);
247 citationStyleLA->setEnabled(haveSelection);
251 void GuiCitation::updateStyle()
253 string const & command = params_.getCmdName();
255 // Find the style of the citekeys
256 vector<CiteStyle> const & styles = citeStyles_;
257 CitationStyle const cs = citationStyleFromString(command);
259 vector<CiteStyle>::const_iterator cit =
260 std::find(styles.begin(), styles.end(), cs.style);
262 // restore the latest natbib style
263 if (style_ >= 0 && style_ < citationStyleCO->count())
264 citationStyleCO->setCurrentIndex(style_);
266 citationStyleCO->setCurrentIndex(0);
268 if (cit != styles.end()) {
269 int const i = int(cit - styles.begin());
270 citationStyleCO->setCurrentIndex(i);
271 fulllistCB->setChecked(cs.full);
272 forceuppercaseCB->setChecked(cs.forceUpperCase);
274 fulllistCB->setChecked(false);
275 forceuppercaseCB->setChecked(false);
277 updateFormatting(cs.style);
280 // This one needs to be called whenever citationStyleCO needs
281 // to be updated---and this would be on anything that changes the
282 // selection in selectedLV, or on a general update.
283 void GuiCitation::fillStyles(BiblioInfo const & bi)
285 int const oldIndex = citationStyleCO->currentIndex();
287 citationStyleCO->clear();
289 QStringList selected_keys = selected_model_.stringList();
290 if (selected_keys.empty()) {
291 citationStyleCO->setEnabled(false);
292 citationStyleLA->setEnabled(false);
296 int curr = selectedLV->model()->rowCount() - 1;
300 if (!selectedLV->selectionModel()->selectedIndexes().empty())
301 curr = selectedLV->selectionModel()->selectedIndexes()[0].row();
303 QStringList sty = citationStyles(bi, curr);
305 citationStyleCO->setEnabled(!sty.isEmpty());
306 citationStyleLA->setEnabled(!sty.isEmpty());
311 citationStyleCO->insertItems(0, sty);
313 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
314 citationStyleCO->setCurrentIndex(oldIndex);
318 void GuiCitation::fillFields(BiblioInfo const & bi)
320 fieldsCO->blockSignals(true);
321 int const oldIndex = fieldsCO->currentIndex();
323 QStringList const fields = to_qstring_list(bi.getFields());
324 fieldsCO->insertItem(0, qt_("All Fields"));
325 fieldsCO->insertItem(1, qt_("Keys"));
326 fieldsCO->insertItems(2, fields);
327 if (oldIndex != -1 && oldIndex < fieldsCO->count())
328 fieldsCO->setCurrentIndex(oldIndex);
329 fieldsCO->blockSignals(false);
333 void GuiCitation::fillEntries(BiblioInfo const & bi)
335 entriesCO->blockSignals(true);
336 int const oldIndex = entriesCO->currentIndex();
338 QStringList const entries = to_qstring_list(bi.getEntries());
339 entriesCO->insertItem(0, qt_("All Entry Types"));
340 entriesCO->insertItems(1, entries);
341 if (oldIndex != -1 && oldIndex < entriesCO->count())
342 entriesCO->setCurrentIndex(oldIndex);
343 entriesCO->blockSignals(false);
347 bool GuiCitation::isSelected(const QModelIndex & idx)
349 QString const str = idx.data().toString();
350 return selected_model_.stringList().contains(str);
354 void GuiCitation::setButtons()
356 selectionManager->update();
357 int const srows = selectedLV->model()->rowCount();
358 applyPB->setEnabled(srows > 0);
359 okPB->setEnabled(srows > 0);
363 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
365 if (!idx.isValid() || bi.empty()) {
366 infoML->document()->clear();
370 QString const keytxt = toqstr(
371 bi.getInfo(qstring_to_ucs4(idx.data().toString())));
372 infoML->document()->setPlainText(keytxt);
376 void GuiCitation::findText(QString const & text, bool reset)
378 //"All Fields" and "Keys" are the first two
379 int index = fieldsCO->currentIndex() - 2;
380 BiblioInfo const & bi = bibInfo();
381 vector<docstring> const & fields = bi.getFields();
384 if (index <= -1 || index >= int(fields.size()))
385 //either "All Fields" or "Keys" or an invalid value
386 field = from_ascii("");
388 field = fields[index];
391 bool const onlyKeys = index == -1;
393 //"All Entry Types" is first.
394 index = entriesCO->currentIndex() - 1;
395 vector<docstring> const & entries = bi.getEntries();
396 docstring entry_type;
397 if (index < 0 || index >= int(entries.size()))
398 entry_type = from_ascii("");
400 entry_type = entries[index];
402 bool const case_sentitive = caseCB->checkState();
403 bool const reg_exp = regexCB->checkState();
404 findKey(bi, text, onlyKeys, field, entry_type,
405 case_sentitive, reg_exp, reset);
407 //It'd be nice to save and restore the current selection in
408 //availableLV. Currently, we get an automatic reset, since the
415 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
417 findText(findLE->text(), true);
421 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
423 findText(findLE->text(), true);
427 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
429 if (index >= 0 && index < citationStyleCO->count()) {
430 vector<CiteStyle> const & styles = citeStyles_;
431 updateFormatting(styles[index]);
436 void GuiCitation::on_findLE_textChanged(const QString & text)
438 bool const searchAsWeGo = (asTypeCB->checkState() == Qt::Checked);
439 searchPB->setDisabled(text.isEmpty() || searchAsWeGo);
440 if (!text.isEmpty()) {
442 findText(findLE->text());
445 findText(findLE->text());
449 void GuiCitation::on_searchPB_clicked()
451 findText(findLE->text(), true);
455 void GuiCitation::on_caseCB_stateChanged(int)
457 findText(findLE->text());
461 void GuiCitation::on_regexCB_stateChanged(int)
463 findText(findLE->text());
467 void GuiCitation::on_asTypeCB_stateChanged(int)
469 bool const searchAsWeGo = (asTypeCB->checkState() == Qt::Checked);
470 searchPB->setDisabled(findLE->text().isEmpty() || searchAsWeGo);
472 findText(findLE->text(), true);
476 void GuiCitation::changed()
482 void GuiCitation::apply(int const choice, bool full, bool force,
483 QString before, QString after)
485 if (cited_keys_.isEmpty())
488 vector<CiteStyle> const & styles = citeStyles_;
489 if (styles[choice] == NOCITE) {
497 s.style = styles[choice];
499 s.forceUpperCase = force;
500 string const command = citationStyleToString(s);
502 params_.setCmdName(command);
503 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
504 params_["before"] = qstring_to_ucs4(before);
505 params_["after"] = qstring_to_ucs4(after);
510 void GuiCitation::clearSelection()
513 selected_model_.setStringList(cited_keys_);
517 void GuiCitation::init()
519 // Make the list of all available bibliography keys
520 BiblioInfo const & bi = bibInfo();
521 all_keys_ = to_qstring_list(bi.getKeys());
522 available_model_.setStringList(all_keys_);
524 // Ditto for the keys cited in this inset
525 QString str = toqstr(params_["key"]);
529 cited_keys_ = str.split(",");
530 selected_model_.setStringList(cited_keys_);
537 void GuiCitation::findKey(BiblioInfo const & bi,
538 QString const & str, bool only_keys,
539 docstring field, docstring entry_type,
540 bool case_sensitive, bool reg_exp, bool reset)
542 // Used for optimisation: store last searched string.
543 static QString last_searched_string;
544 // Used to disable the above optimisation.
545 static bool last_case_sensitive;
546 static bool last_reg_exp;
547 // Reset last_searched_string in case of changed option.
548 if (last_case_sensitive != case_sensitive
549 || last_reg_exp != reg_exp) {
550 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
551 last_searched_string.clear();
553 // save option for next search.
554 last_case_sensitive = case_sensitive;
555 last_reg_exp = reg_exp;
557 Qt::CaseSensitivity qtcase = case_sensitive ?
558 Qt::CaseSensitive: Qt::CaseInsensitive;
560 // If new string (str) contains the last searched one...
562 !last_searched_string.isEmpty() &&
564 str.contains(last_searched_string, qtcase))
565 // ... then only search within already found list.
566 keys = available_model_.stringList();
568 // ... else search all keys.
570 // save searched string for next search.
571 last_searched_string = str;
575 // First, filter by entry_type, which will be faster than
576 // what follows, so we may get to do that on less.
577 vector<docstring> keyVector = to_docstring_vector(keys);
578 filterByEntryType(bi, keyVector, entry_type);
581 result = to_qstring_list(keyVector);
583 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
584 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
586 available_model_.setStringList(result);
590 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, int sel)
592 docstring const key = qstring_to_ucs4(cited_keys_[sel]);
593 return to_qstring_list(bi.getCiteStrings(key, buffer()));
597 void GuiCitation::setCitedKeys()
599 cited_keys_ = selected_model_.stringList();
603 bool GuiCitation::initialiseParams(string const & data)
605 InsetCommand::string2params("citation", data, params_);
606 CiteEngine const engine = buffer().params().citeEngine();
607 citeStyles_ = citeStyles(engine);
613 void GuiCitation::clearParams()
619 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
620 vector<docstring> & keyVector, docstring entry_type)
622 if (entry_type.empty())
625 vector<docstring>::iterator it = keyVector.begin();
626 vector<docstring>::iterator end = keyVector.end();
628 vector<docstring> result;
629 for (; it != end; ++it) {
630 docstring const key = *it;
631 BiblioInfo::const_iterator cit = bi.find(key);
634 if (cit->second.entryType() == entry_type)
635 result.push_back(key);
641 CiteEngine GuiCitation::citeEngine() const
643 return buffer().params().citeEngine();
647 // Escape special chars.
648 // All characters are literals except: '.|*?+(){}[]^$\'
649 // These characters are literals when preceded by a "\", which is done here
650 // @todo: This function should be moved to support, and then the test in tests
651 // should be moved there as well.
652 static docstring escape_special_chars(docstring const & expr)
654 // Search for all chars '.|*?+(){}[^$]\'
655 // Note that '[' and '\' must be escaped.
656 // This is a limitation of boost::regex, but all other chars in BREs
657 // are assumed literal.
658 static const boost::regex reg("[].|*?+(){}^$\\[\\\\]");
660 // $& is a perl-like expression that expands to all
661 // of the current match
662 // The '$' must be prefixed with the escape character '\' for
663 // boost to treat it as a literal.
664 // Thus, to prefix a matched expression with '\', we use:
666 return from_utf8(boost::regex_replace(to_utf8(expr), reg, "\\\\$&"));
670 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
671 vector<docstring> const & keys_to_search, bool only_keys,
672 docstring const & search_expression, docstring field,
673 bool case_sensitive, bool regex)
675 vector<docstring> foundKeys;
677 docstring expr = trim(search_expression);
682 // We must escape special chars in the search_expr so that
683 // it is treated as a simple string by boost::regex.
684 expr = escape_special_chars(expr);
686 boost::regex reg_exp;
688 reg_exp.assign(to_utf8(expr), case_sensitive ?
689 boost::regex_constants::normal : boost::regex_constants::icase);
690 } catch (boost::regex_error & e) {
691 // boost::regex throws an exception if the regular expression is not
693 LYXERR(Debug::GUI, e.what());
694 return vector<docstring>();
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 = bi.find(*it);
701 if (info == bi.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[field]);
717 if (boost::regex_search(data, reg_exp))
718 foundKeys.push_back(*it);
720 catch (boost::regex_error & e) {
721 LYXERR(Debug::GUI, e.what());
722 return vector<docstring>();
729 void GuiCitation::dispatchParams()
731 std::string const lfun = InsetCommand::params2string("citation", params_);
732 dispatch(FuncRequest(getLfun(), lfun));
736 BiblioInfo const & GuiCitation::bibInfo() const
738 return buffer().masterBibInfo();
742 void GuiCitation::saveSession() const
744 Dialog::saveSession();
747 sessionKey() + "/regex", regexCB->isChecked());
749 sessionKey() + "/casesensitive", caseCB->isChecked());
751 sessionKey() + "/autofind", asTypeCB->isChecked());
755 void GuiCitation::restoreSession()
757 Dialog::restoreSession();
760 settings.value(sessionKey() + "/regex").toBool());
762 settings.value(sessionKey() + "/casesensitive").toBool());
763 asTypeCB->setChecked(
764 settings.value(sessionKey() + "/autofind").toBool());
768 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
771 } // namespace frontend
774 #include "moc_GuiCitation.cpp"