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<biblio::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(clearPB, SIGNAL(clicked()),
96 findLE, SLOT(clear()));
97 connect(this, SIGNAL(rejected()), this, SLOT(cleanUp()));
99 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
100 addPB, deletePB, upPB, downPB, available(), selected());
101 connect(selectionManager, SIGNAL(selectionChanged()),
102 this, SLOT(setCitedKeys()));
103 connect(selectionManager, SIGNAL(updateHook()),
104 this, SLOT(updateDialog()));
105 connect(selectionManager, SIGNAL(okHook()),
106 this, SLOT(on_okPB_clicked()));
108 bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
112 void GuiCitation::cleanUp()
120 void GuiCitation::closeEvent(QCloseEvent * e)
128 void GuiCitation::applyView()
130 int const choice = max(0, citationStyleCO->currentIndex());
132 bool const full = fulllistCB->isChecked();
133 bool const force = forceuppercaseCB->isChecked();
135 QString const before = textBeforeED->text();
136 QString const after = textAfterED->text();
138 apply(choice, full, force, before, after);
142 void GuiCitation::showEvent(QShowEvent * e)
146 availableLV->setFocus();
147 GuiDialog::showEvent(e);
151 void GuiCitation::on_okPB_clicked()
159 void GuiCitation::on_cancelPB_clicked()
166 void GuiCitation::on_applyPB_clicked()
172 void GuiCitation::on_restorePB_clicked()
179 void GuiCitation::updateView()
188 // The main point of separating this out is that the fill*() methods
189 // called in update() do not need to be called for INTERNAL updates,
190 // such as when addPB is pressed, as the list of fields, entries, etc,
191 // will not have changed. At the moment, however, the division between
192 // fillStyles() and updateStyle() doesn't lend itself to dividing the
193 // two methods, though they should be divisible.
194 void GuiCitation::updateDialog()
196 if (selectionManager->selectedFocused()) {
197 if (selectedLV->selectionModel()->selectedIndexes().isEmpty())
198 updateInfo(availableLV->currentIndex());
200 updateInfo(selectedLV->currentIndex());
202 if (availableLV->selectionModel()->selectedIndexes().isEmpty())
203 updateInfo(QModelIndex());
205 updateInfo(availableLV->currentIndex());
209 textBeforeED->setText(textBefore());
210 textAfterED->setText(textAfter());
216 void GuiCitation::updateFormatting(biblio::CiteStyle currentStyle)
218 biblio::CiteEngine const engine = citeEngine();
219 bool const natbib_engine =
220 engine == biblio::ENGINE_NATBIB_AUTHORYEAR ||
221 engine == biblio::ENGINE_NATBIB_NUMERICAL;
222 bool const basic_engine = engine == biblio::ENGINE_BASIC;
224 bool const haveSelection =
225 selectedLV->model()->rowCount() > 0;
227 bool const isNocite = currentStyle == biblio::NOCITE;
229 fulllistCB->setEnabled(natbib_engine && haveSelection && !isNocite);
230 forceuppercaseCB->setEnabled(natbib_engine && haveSelection && !isNocite);
231 textBeforeED->setEnabled(!basic_engine && haveSelection && !isNocite);
232 textBeforeLA->setEnabled(!basic_engine && haveSelection && !isNocite);
233 textAfterED->setEnabled(haveSelection && !isNocite);
234 textAfterLA->setEnabled(haveSelection && !isNocite);
235 citationStyleCO->setEnabled(haveSelection);
236 citationStyleLA->setEnabled(haveSelection);
240 void GuiCitation::updateStyle()
242 string const & command = params_.getCmdName();
244 // Find the style of the citekeys
245 vector<biblio::CiteStyle> const & styles = citeStyles_;
246 biblio::CitationStyle const cs(command);
248 vector<biblio::CiteStyle>::const_iterator cit =
249 std::find(styles.begin(), styles.end(), cs.style);
251 // restore the latest natbib style
252 if (style_ >= 0 && style_ < citationStyleCO->count())
253 citationStyleCO->setCurrentIndex(style_);
255 citationStyleCO->setCurrentIndex(0);
257 if (cit != styles.end()) {
258 int const i = int(cit - styles.begin());
259 citationStyleCO->setCurrentIndex(i);
260 fulllistCB->setChecked(cs.full);
261 forceuppercaseCB->setChecked(cs.forceUCase);
263 fulllistCB->setChecked(false);
264 forceuppercaseCB->setChecked(false);
266 updateFormatting(cs.style);
269 //This one needs to be called whenever citationStyleCO needs
270 //to be updated---and this would be on anything that changes the
271 //selection in selectedLV, or on a general update.
272 void GuiCitation::fillStyles()
274 int const oldIndex = citationStyleCO->currentIndex();
276 citationStyleCO->clear();
278 QStringList selected_keys = selected()->stringList();
279 if (selected_keys.empty()) {
280 citationStyleCO->setEnabled(false);
281 citationStyleLA->setEnabled(false);
285 int curr = selectedLV->model()->rowCount() - 1;
289 if (!selectedLV->selectionModel()->selectedIndexes().empty())
290 curr = selectedLV->selectionModel()->selectedIndexes()[0].row();
292 QStringList sty = citationStyles(curr);
294 citationStyleCO->setEnabled(!sty.isEmpty());
295 citationStyleLA->setEnabled(!sty.isEmpty());
300 citationStyleCO->insertItems(0, sty);
302 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
303 citationStyleCO->setCurrentIndex(oldIndex);
307 void GuiCitation::fillFields()
309 fieldsCO->blockSignals(true);
310 int const oldIndex = fieldsCO->currentIndex();
312 QStringList const & fields = getFieldsAsQStringList();
313 fieldsCO->insertItem(0, qt_("All Fields"));
314 fieldsCO->insertItem(1, qt_("Keys"));
315 fieldsCO->insertItems(2, fields);
316 if (oldIndex != -1 && oldIndex < fieldsCO->count())
317 fieldsCO->setCurrentIndex(oldIndex);
318 fieldsCO->blockSignals(false);
322 void GuiCitation::fillEntries()
324 entriesCO->blockSignals(true);
325 int const oldIndex = entriesCO->currentIndex();
327 QStringList const & entries = getEntriesAsQStringList();
328 entriesCO->insertItem(0, qt_("All Entry Types"));
329 entriesCO->insertItems(1, entries);
330 if (oldIndex != -1 && oldIndex < entriesCO->count())
331 entriesCO->setCurrentIndex(oldIndex);
332 entriesCO->blockSignals(false);
336 bool GuiCitation::isSelected(const QModelIndex & idx)
338 QString const str = idx.data().toString();
339 return selected()->stringList().contains(str);
343 void GuiCitation::setButtons()
345 selectionManager->update();
346 int const srows = selectedLV->model()->rowCount();
347 applyPB->setEnabled(srows > 0);
348 okPB->setEnabled(srows > 0);
352 void GuiCitation::updateInfo(QModelIndex const & idx)
355 QString const keytxt = getKeyInfo(idx.data().toString());
356 infoML->document()->setPlainText(keytxt);
358 infoML->document()->clear();
362 void GuiCitation::findText(QString const & text, bool reset)
364 //"All Fields" and "Keys" are the first two
365 int index = fieldsCO->currentIndex() - 2;
366 vector<docstring> const & fields = availableFields();
369 if (index <= -1 || index >= int(fields.size()))
370 //either "All Fields" or "Keys" or an invalid value
371 field = from_ascii("");
373 field = fields[index];
376 bool const onlyKeys = index == -1;
378 //"All Entry Types" is first.
379 index = entriesCO->currentIndex() - 1;
380 vector<docstring> const & entries = availableEntries();
381 docstring entry_type;
382 if (index < 0 || index >= int(entries.size()))
383 entry_type = from_ascii("");
385 entry_type = entries[index];
387 bool const case_sentitive = caseCB->checkState();
388 bool const reg_exp = regexCB->checkState();
389 findKey(text, onlyKeys, field, entry_type,
390 case_sentitive, reg_exp, reset);
392 //It'd be nice to save and restore the current selection in
393 //availableLV. Currently, we get an automatic reset, since the
400 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
402 findText(findLE->text(), true);
406 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
408 findText(findLE->text(), true);
412 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
414 if (index >= 0 && index < citationStyleCO->count()) {
415 vector<biblio::CiteStyle> const & styles = citeStyles_;
416 updateFormatting(styles[index]);
421 void GuiCitation::on_findLE_textChanged(const QString & text)
423 clearPB->setDisabled(text.isEmpty());
430 void GuiCitation::on_caseCB_stateChanged(int)
432 findText(findLE->text());
436 void GuiCitation::on_regexCB_stateChanged(int)
438 findText(findLE->text());
442 void GuiCitation::changed()
448 void GuiCitation::apply(int const choice, bool full, bool force,
449 QString before, QString after)
451 if (cited_keys_.isEmpty())
454 vector<biblio::CiteStyle> const & styles = citeStyles_;
455 if (styles[choice] == biblio::NOCITE) {
462 string const command =
463 biblio::CitationStyle(styles[choice], full, force)
466 params_.setCmdName(command);
467 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
468 params_["before"] = qstring_to_ucs4(before);
469 params_["after"] = qstring_to_ucs4(after);
474 void GuiCitation::clearSelection()
477 selected_model_.setStringList(cited_keys_);
481 QString GuiCitation::textBefore()
483 return toqstr(params_["before"]);
487 QString GuiCitation::textAfter()
489 return toqstr(params_["after"]);
493 void GuiCitation::init()
495 // Make the list of all available bibliography keys
496 all_keys_ = to_qstring_list(availableKeys());
497 available_model_.setStringList(all_keys_);
499 // Ditto for the keys cited in this inset
500 QString str = toqstr(params_["key"]);
504 cited_keys_ = str.split(",");
505 selected_model_.setStringList(cited_keys_);
509 void GuiCitation::findKey(QString const & str, bool only_keys,
510 docstring field, docstring entry_type,
511 bool case_sensitive, bool reg_exp, bool reset)
513 // Used for optimisation: store last searched string.
514 static QString last_searched_string;
515 // Used to disable the above optimisation.
516 static bool last_case_sensitive;
517 static bool last_reg_exp;
518 // Reset last_searched_string in case of changed option.
519 if (last_case_sensitive != case_sensitive
520 || last_reg_exp != reg_exp) {
521 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
522 last_searched_string.clear();
524 // save option for next search.
525 last_case_sensitive = case_sensitive;
526 last_reg_exp = reg_exp;
528 Qt::CaseSensitivity qtcase = case_sensitive?
529 Qt::CaseSensitive: Qt::CaseInsensitive;
531 // If new string (str) contains the last searched one...
533 !last_searched_string.isEmpty() &&
535 str.contains(last_searched_string, qtcase))
536 // ... then only search within already found list.
537 keys = available_model_.stringList();
539 // ... else search all keys.
541 // save searched string for next search.
542 last_searched_string = str;
546 // First, filter by entry_type, which will be faster than
547 // what follows, so we may get to do that on less.
548 vector<docstring> keyVector = to_docstring_vector(keys);
549 filterByEntryType(keyVector, entry_type);
552 result = to_qstring_list(keyVector);
554 result = to_qstring_list(searchKeys(keyVector, only_keys,
555 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
557 available_model_.setStringList(result);
561 QStringList GuiCitation::getFieldsAsQStringList()
563 return to_qstring_list(availableFields());
567 QStringList GuiCitation::getEntriesAsQStringList()
569 return to_qstring_list(availableEntries());
573 QStringList GuiCitation::citationStyles(int sel)
575 docstring const key = qstring_to_ucs4(cited_keys_[sel]);
576 return to_qstring_list(bibkeysInfo_.getCiteStrings(key, buffer()));
580 QString GuiCitation::getKeyInfo(QString const & sel)
582 return toqstr(getInfo(qstring_to_ucs4(sel)));
586 void GuiCitation::setCitedKeys()
588 cited_keys_ = selected_model_.stringList();
592 bool GuiCitation::initialiseParams(string const & data)
594 InsetCommand::string2params("citation", data, params_);
595 biblio::CiteEngine const engine = buffer().params().citeEngine();
596 bibkeysInfo_.fillWithBibKeys(&buffer());
597 citeStyles_ = biblio::getCiteStyles(engine);
602 void GuiCitation::clearParams()
605 bibkeysInfo_.clear();
609 vector<docstring> GuiCitation::availableKeys() const
611 return bibkeysInfo_.getKeys();
615 vector<docstring> GuiCitation::availableFields() const
617 return bibkeysInfo_.getFields();
621 vector<docstring> GuiCitation::availableEntries() const
623 return bibkeysInfo_.getEntries();
627 void GuiCitation::filterByEntryType(
628 vector<docstring> & keyVector, docstring entry_type)
630 if (entry_type.empty())
633 vector<docstring>::iterator it = keyVector.begin();
634 vector<docstring>::iterator end = keyVector.end();
636 vector<docstring> result;
637 for (; it != end; ++it) {
638 docstring const key = *it;
639 BiblioInfo::const_iterator cit = bibkeysInfo_.find(key);
640 if (cit == bibkeysInfo_.end())
642 if (cit->second.entryType() == entry_type)
643 result.push_back(key);
649 biblio::CiteEngine GuiCitation::citeEngine() const
651 return buffer().params().citeEngine();
655 docstring GuiCitation::getInfo(docstring const & key) const
657 if (bibkeysInfo_.empty())
660 return bibkeysInfo_.getInfo(key);
664 // Escape special chars.
665 // All characters are literals except: '.|*?+(){}[]^$\'
666 // These characters are literals when preceded by a "\", which is done here
667 // @todo: This function should be moved to support, and then the test in tests
668 // should be moved there as well.
669 static docstring escape_special_chars(docstring const & expr)
671 // Search for all chars '.|*?+(){}[^$]\'
672 // Note that '[' and '\' must be escaped.
673 // This is a limitation of boost::regex, but all other chars in BREs
674 // are assumed literal.
675 static const boost::regex reg("[].|*?+(){}^$\\[\\\\]");
677 // $& is a perl-like expression that expands to all
678 // of the current match
679 // The '$' must be prefixed with the escape character '\' for
680 // boost to treat it as a literal.
681 // Thus, to prefix a matched expression with '\', we use:
683 return from_utf8(boost::regex_replace(to_utf8(expr), reg, "\\\\$&"));
687 vector<docstring> GuiCitation::searchKeys(
688 vector<docstring> const & keys_to_search, bool only_keys,
689 docstring const & search_expression, docstring field,
690 bool case_sensitive, bool regex)
692 vector<docstring> foundKeys;
694 docstring expr = trim(search_expression);
699 // We must escape special chars in the search_expr so that
700 // it is treated as a simple string by boost::regex.
701 expr = escape_special_chars(expr);
703 boost::regex reg_exp;
705 reg_exp.assign(to_utf8(expr), case_sensitive ?
706 boost::regex_constants::normal : boost::regex_constants::icase);
707 } catch (boost::regex_error & e) {
708 // boost::regex throws an exception if the regular expression is not
710 LYXERR(Debug::GUI, e.what());
711 return vector<docstring>();
714 vector<docstring>::const_iterator it = keys_to_search.begin();
715 vector<docstring>::const_iterator end = keys_to_search.end();
716 for (; it != end; ++it ) {
717 BiblioInfo::const_iterator info = bibkeysInfo_.find(*it);
718 if (info == bibkeysInfo_.end())
721 BibTeXInfo const & kvm = info->second;
725 else if (field.empty())
726 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
727 else if (kvm.hasField(field))
728 data = to_utf8(kvm.getValueForField(field));
734 if (boost::regex_search(data, reg_exp))
735 foundKeys.push_back(*it);
737 catch (boost::regex_error & e) {
738 LYXERR(Debug::GUI, e.what());
739 return vector<docstring>();
746 void GuiCitation::dispatchParams()
748 std::string const lfun = InsetCommand::params2string("citation", params_);
749 dispatch(FuncRequest(getLfun(), lfun));
753 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
756 } // namespace frontend
759 #include "GuiCitation_moc.cpp"