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 "support/debug.h"
19 #include "support/gettext.h"
20 #include "qt_helpers.h"
22 #include "BufferParams.h"
24 #include "support/lstrings.h"
25 #include "support/docstring.h"
27 #include "insets/InsetCommand.h"
32 #include <QCloseEvent>
37 #include <boost/regex.hpp>
44 using namespace lyx::support;
49 static vector<biblio::CiteStyle> citeStyles_;
52 template<typename String>
53 static QStringList to_qstring_list(vector<String> const & v)
57 for (size_t i = 0; i != v.size(); ++i) {
60 qlist.append(lyx::toqstr(v[i]));
66 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
68 vector<lyx::docstring> v;
69 for (int i = 0; i != qlist.size(); ++i) {
70 if (qlist[i].isEmpty())
72 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
78 GuiCitation::GuiCitation(GuiView & lv)
79 : GuiCommand(lv, "citation")
82 setViewTitle(_("Citation"));
84 connect(citationStyleCO, SIGNAL(activated(int)),
85 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
86 connect(fulllistCB, SIGNAL(clicked()),
87 this, SLOT(changed()));
88 connect(forceuppercaseCB, SIGNAL(clicked()),
89 this, SLOT(changed()));
90 connect(textBeforeED, SIGNAL(textChanged(QString)),
91 this, SLOT(changed()));
92 connect(textAfterED, SIGNAL(textChanged(QString)),
93 this, SLOT(changed()));
94 connect(clearPB, SIGNAL(clicked()),
95 findLE, SLOT(clear()));
96 connect(this, SIGNAL(rejected()), this, SLOT(cleanUp()));
98 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
99 addPB, deletePB, upPB, downPB, available(), selected());
100 connect(selectionManager, SIGNAL(selectionChanged()),
101 this, SLOT(setCitedKeys()));
102 connect(selectionManager, SIGNAL(updateHook()),
103 this, SLOT(updateDialog()));
104 connect(selectionManager, SIGNAL(okHook()),
105 this, SLOT(on_okPB_clicked()));
107 bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
111 void GuiCitation::cleanUp()
119 void GuiCitation::closeEvent(QCloseEvent * e)
123 GuiDialog::closeEvent(e);
127 void GuiCitation::applyView()
129 int const choice = max(0, citationStyleCO->currentIndex());
131 bool const full = fulllistCB->isChecked();
132 bool const force = forceuppercaseCB->isChecked();
134 QString const before = textBeforeED->text();
135 QString const after = textAfterED->text();
137 apply(choice, full, force, before, after);
141 void GuiCitation::showEvent(QShowEvent * e)
145 availableLV->setFocus();
146 GuiDialog::showEvent(e);
150 void GuiCitation::on_okPB_clicked()
158 void GuiCitation::on_cancelPB_clicked()
165 void GuiCitation::on_applyPB_clicked()
171 void GuiCitation::on_restorePB_clicked()
178 void GuiCitation::updateView()
187 // The main point of separating this out is that the fill*() methods
188 // called in update() do not need to be called for INTERNAL updates,
189 // such as when addPB is pressed, as the list of fields, entries, etc,
190 // will not have changed. At the moment, however, the division between
191 // fillStyles() and updateStyle() doesn't lend itself to dividing the
192 // two methods, though they should be divisible.
193 void GuiCitation::updateDialog()
195 if (selectionManager->selectedFocused()) {
196 if (selectedLV->selectionModel()->selectedIndexes().isEmpty())
197 updateInfo(availableLV->currentIndex());
199 updateInfo(selectedLV->currentIndex());
201 if (availableLV->selectionModel()->selectedIndexes().isEmpty())
202 updateInfo(QModelIndex());
204 updateInfo(availableLV->currentIndex());
208 textBeforeED->setText(textBefore());
209 textAfterED->setText(textAfter());
215 void GuiCitation::updateFormatting(biblio::CiteStyle currentStyle)
217 biblio::CiteEngine const engine = getEngine();
218 bool const natbib_engine =
219 engine == biblio::ENGINE_NATBIB_AUTHORYEAR ||
220 engine == biblio::ENGINE_NATBIB_NUMERICAL;
221 bool const basic_engine = engine == biblio::ENGINE_BASIC;
223 bool const haveSelection =
224 selectedLV->model()->rowCount() > 0;
226 bool const isNocite = currentStyle == biblio::NOCITE;
228 fulllistCB->setEnabled(natbib_engine && haveSelection && !isNocite);
229 forceuppercaseCB->setEnabled(natbib_engine && haveSelection && !isNocite);
230 textBeforeED->setEnabled(!basic_engine && haveSelection && !isNocite);
231 textBeforeLA->setEnabled(!basic_engine && haveSelection && !isNocite);
232 textAfterED->setEnabled(haveSelection && !isNocite);
233 textAfterLA->setEnabled(haveSelection && !isNocite);
234 citationStyleCO->setEnabled(haveSelection);
235 citationStyleLA->setEnabled(haveSelection);
239 void GuiCitation::updateStyle()
241 string const & command = params_.getCmdName();
243 // Find the style of the citekeys
244 vector<biblio::CiteStyle> const & styles = citeStyles_;
245 biblio::CitationStyle const cs(command);
247 vector<biblio::CiteStyle>::const_iterator cit =
248 std::find(styles.begin(), styles.end(), cs.style);
250 // restore the latest natbib style
251 if (style_ >= 0 && style_ < citationStyleCO->count())
252 citationStyleCO->setCurrentIndex(style_);
254 citationStyleCO->setCurrentIndex(0);
256 if (cit != styles.end()) {
257 int const i = int(cit - styles.begin());
258 citationStyleCO->setCurrentIndex(i);
259 fulllistCB->setChecked(cs.full);
260 forceuppercaseCB->setChecked(cs.forceUCase);
262 fulllistCB->setChecked(false);
263 forceuppercaseCB->setChecked(false);
265 updateFormatting(cs.style);
268 //This one needs to be called whenever citationStyleCO needs
269 //to be updated---and this would be on anything that changes the
270 //selection in selectedLV, or on a general update.
271 void GuiCitation::fillStyles()
273 int const oldIndex = citationStyleCO->currentIndex();
275 citationStyleCO->clear();
277 QStringList selected_keys = selected()->stringList();
278 if (selected_keys.empty()) {
279 citationStyleCO->setEnabled(false);
280 citationStyleLA->setEnabled(false);
284 int curr = selectedLV->model()->rowCount() - 1;
288 if (!selectedLV->selectionModel()->selectedIndexes().empty())
289 curr = selectedLV->selectionModel()->selectedIndexes()[0].row();
291 QStringList sty = citationStyles(curr);
293 citationStyleCO->setEnabled(!sty.isEmpty());
294 citationStyleLA->setEnabled(!sty.isEmpty());
299 citationStyleCO->insertItems(0, sty);
301 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
302 citationStyleCO->setCurrentIndex(oldIndex);
306 void GuiCitation::fillFields()
308 fieldsCO->blockSignals(true);
309 int const oldIndex = fieldsCO->currentIndex();
311 QStringList const & fields = getFieldsAsQStringList();
312 fieldsCO->insertItem(0, qt_("All Fields"));
313 fieldsCO->insertItem(1, qt_("Keys"));
314 fieldsCO->insertItems(2, fields);
315 if (oldIndex != -1 && oldIndex < fieldsCO->count())
316 fieldsCO->setCurrentIndex(oldIndex);
317 fieldsCO->blockSignals(false);
321 void GuiCitation::fillEntries()
323 entriesCO->blockSignals(true);
324 int const oldIndex = entriesCO->currentIndex();
326 QStringList const & entries = getEntriesAsQStringList();
327 entriesCO->insertItem(0, qt_("All Entry Types"));
328 entriesCO->insertItems(1, entries);
329 if (oldIndex != -1 && oldIndex < entriesCO->count())
330 entriesCO->setCurrentIndex(oldIndex);
331 entriesCO->blockSignals(false);
335 bool GuiCitation::isSelected(const QModelIndex & idx)
337 QString const str = idx.data().toString();
338 return selected()->stringList().contains(str);
342 void GuiCitation::setButtons()
344 selectionManager->update();
345 int const srows = selectedLV->model()->rowCount();
346 applyPB->setEnabled(srows > 0);
347 okPB->setEnabled(srows > 0);
351 void GuiCitation::updateInfo(QModelIndex const & idx)
354 QString const keytxt = getKeyInfo(idx.data().toString());
355 infoML->document()->setPlainText(keytxt);
357 infoML->document()->clear();
361 void GuiCitation::findText(QString const & text, bool reset)
363 //"All Fields" and "Keys" are the first two
364 int index = fieldsCO->currentIndex() - 2;
365 vector<docstring> const & fields = availableFields();
368 if (index <= -1 || index >= int(fields.size()))
369 //either "All Fields" or "Keys" or an invalid value
370 field = from_ascii("");
372 field = fields[index];
375 bool const onlyKeys = index == -1;
377 //"All Entry Types" is first.
378 index = entriesCO->currentIndex() - 1;
379 vector<docstring> const & entries = availableEntries();
381 if (index < 0 || index >= int(entries.size()))
382 entryType = from_ascii("");
384 entryType = entries[index];
386 bool const case_sentitive = caseCB->checkState();
387 bool const reg_exp = regexCB->checkState();
388 findKey(text, onlyKeys, field, entryType,
389 case_sentitive, reg_exp, reset);
391 //It'd be nice to save and restore the current selection in
392 //availableLV. Currently, we get an automatic reset, since the
399 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
401 findText(findLE->text(), true);
405 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
407 findText(findLE->text(), true);
411 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
413 if (index >= 0 && index < citationStyleCO->count()) {
414 vector<biblio::CiteStyle> const & styles = citeStyles_;
415 updateFormatting(styles[index]);
420 void GuiCitation::on_findLE_textChanged(const QString & text)
422 clearPB->setDisabled(text.isEmpty());
429 void GuiCitation::on_caseCB_stateChanged(int)
431 findText(findLE->text());
435 void GuiCitation::on_regexCB_stateChanged(int)
437 findText(findLE->text());
441 void GuiCitation::changed()
447 void GuiCitation::apply(int const choice, bool full, bool force,
448 QString before, QString after)
450 if (cited_keys_.isEmpty())
453 vector<biblio::CiteStyle> const & styles = citeStyles_;
454 if (styles[choice] == biblio::NOCITE) {
461 string const command =
462 biblio::CitationStyle(styles[choice], full, force)
465 params_.setCmdName(command);
466 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
467 params_["before"] = qstring_to_ucs4(before);
468 params_["after"] = qstring_to_ucs4(after);
473 void GuiCitation::clearSelection()
476 selected_model_.setStringList(cited_keys_);
480 QString GuiCitation::textBefore()
482 return toqstr(params_["before"]);
486 QString GuiCitation::textAfter()
488 return toqstr(params_["after"]);
492 void GuiCitation::init()
494 // Make the list of all available bibliography keys
495 all_keys_ = to_qstring_list(availableKeys());
496 available_model_.setStringList(all_keys_);
498 // Ditto for the keys cited in this inset
499 QString str = toqstr(params_["key"]);
503 cited_keys_ = str.split(",");
504 selected_model_.setStringList(cited_keys_);
508 void GuiCitation::findKey(QString const & str, bool only_keys,
509 docstring field, docstring entryType,
510 bool case_sensitive, bool reg_exp, bool reset)
512 // Used for optimisation: store last searched string.
513 static QString last_searched_string;
514 // Used to disable the above optimisation.
515 static bool last_case_sensitive;
516 static bool last_reg_exp;
517 // Reset last_searched_string in case of changed option.
518 if (last_case_sensitive != case_sensitive
519 || last_reg_exp != reg_exp) {
520 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
521 last_searched_string.clear();
523 // save option for next search.
524 last_case_sensitive = case_sensitive;
525 last_reg_exp = reg_exp;
527 Qt::CaseSensitivity qtcase = case_sensitive?
528 Qt::CaseSensitive: Qt::CaseInsensitive;
530 // If new string (str) contains the last searched one...
532 !last_searched_string.isEmpty() &&
534 str.contains(last_searched_string, qtcase))
535 // ... then only search within already found list.
536 keys = available_model_.stringList();
538 // ... else search all keys.
540 // save searched string for next search.
541 last_searched_string = str;
545 // First, filter by entryType, which will be faster than
546 // what follows, so we may get to do that on less.
547 vector<docstring> keyVector = to_docstring_vector(keys);
548 filterByEntryType(keyVector, entryType);
551 result = to_qstring_list(keyVector);
553 result = to_qstring_list(searchKeys(keyVector, only_keys,
554 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
556 available_model_.setStringList(result);
560 QStringList GuiCitation::getFieldsAsQStringList()
562 return to_qstring_list(availableFields());
566 QStringList GuiCitation::getEntriesAsQStringList()
568 return to_qstring_list(availableEntries());
572 QStringList GuiCitation::citationStyles(int sel)
574 docstring const key = qstring_to_ucs4(cited_keys_[sel]);
575 return to_qstring_list(bibkeysInfo_.getCiteStrings(key, buffer()));
579 QString GuiCitation::getKeyInfo(QString const & sel)
581 return toqstr(getInfo(qstring_to_ucs4(sel)));
585 void GuiCitation::setCitedKeys()
587 cited_keys_ = selected_model_.stringList();
591 bool GuiCitation::initialiseParams(string const & data)
593 InsetCommandMailer::string2params(lfun_name_, data, params_);
595 biblio::CiteEngine const engine = buffer().params().getEngine();
597 bibkeysInfo_.fillWithBibKeys(&buffer());
599 citeStyles_ = biblio::getCiteStyles(engine);
605 void GuiCitation::clearParams()
608 bibkeysInfo_.clear();
612 vector<docstring> const GuiCitation::availableKeys() const
614 return bibkeysInfo_.getKeys();
618 vector<docstring> const GuiCitation::availableFields() const
620 return bibkeysInfo_.getFields();
624 vector<docstring> const GuiCitation::availableEntries() const
626 return bibkeysInfo_.getEntries();
630 void GuiCitation::filterByEntryType(
631 vector<docstring> & keyVector, docstring entryType)
633 if (entryType.empty())
636 vector<docstring>::iterator it = keyVector.begin();
637 vector<docstring>::iterator end = keyVector.end();
639 vector<docstring> result;
640 for (; it != end; ++it) {
641 docstring const key = *it;
642 BiblioInfo::const_iterator cit = bibkeysInfo_.find(key);
643 if (cit == bibkeysInfo_.end())
645 if (cit->second.entryType == entryType)
646 result.push_back(key);
652 biblio::CiteEngine GuiCitation::getEngine() const
654 return buffer().params().getEngine();
658 docstring GuiCitation::getInfo(docstring const & key) const
660 if (bibkeysInfo_.empty())
663 return bibkeysInfo_.getInfo(key);
667 // Escape special chars.
668 // All characters are literals except: '.|*?+(){}[]^$\'
669 // These characters are literals when preceded by a "\", which is done here
670 // @todo: This function should be moved to support, and then the test in tests
671 // should be moved there as well.
672 static docstring escape_special_chars(docstring const & expr)
674 // Search for all chars '.|*?+(){}[^$]\'
675 // Note that '[' and '\' must be escaped.
676 // This is a limitation of boost::regex, but all other chars in BREs
677 // are assumed literal.
678 static const boost::regex reg("[].|*?+(){}^$\\[\\\\]");
680 // $& is a perl-like expression that expands to all
681 // of the current match
682 // The '$' must be prefixed with the escape character '\' for
683 // boost to treat it as a literal.
684 // Thus, to prefix a matched expression with '\', we use:
686 return from_utf8(boost::regex_replace(to_utf8(expr), reg, "\\\\$&"));
690 vector<docstring> GuiCitation::searchKeys(
691 vector<docstring> const & keys_to_search, bool only_keys,
692 docstring const & search_expression, docstring field,
693 bool case_sensitive, bool regex)
695 vector<docstring> foundKeys;
697 docstring expr = trim(search_expression);
702 // We must escape special chars in the search_expr so that
703 // it is treated as a simple string by boost::regex.
704 expr = escape_special_chars(expr);
706 boost::regex reg_exp;
708 reg_exp.assign(to_utf8(expr), case_sensitive ?
709 boost::regex_constants::normal : boost::regex_constants::icase);
710 } catch (boost::regex_error & e) {
711 // boost::regex throws an exception if the regular expression is not
713 LYXERR(Debug::GUI, e.what());
714 return vector<docstring>();
717 vector<docstring>::const_iterator it = keys_to_search.begin();
718 vector<docstring>::const_iterator end = keys_to_search.end();
719 for (; it != end; ++it ) {
720 BiblioInfo::const_iterator info = bibkeysInfo_.find(*it);
721 if (info == bibkeysInfo_.end())
724 BibTeXInfo const & kvm = info->second;
728 else if (field.empty())
729 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData);
730 else if (kvm.hasField(field))
731 data = to_utf8(kvm.getValueForField(field));
737 if (boost::regex_search(data, reg_exp))
738 foundKeys.push_back(*it);
740 catch (boost::regex_error & e) {
741 LYXERR(Debug::GUI, e.what());
742 return vector<docstring>();
749 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
752 } // namespace frontend
755 #include "GuiCitation_moc.cpp"