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<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(CiteStyle currentStyle)
218 CiteEngine const engine = citeEngine();
219 bool const natbib_engine =
220 engine == ENGINE_NATBIB_AUTHORYEAR ||
221 engine == ENGINE_NATBIB_NUMERICAL;
222 bool const basic_engine = engine == ENGINE_BASIC;
224 bool const haveSelection =
225 selectedLV->model()->rowCount() > 0;
227 bool const isNocite = currentStyle == 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<CiteStyle> const & styles = citeStyles_;
246 CitationStyle const cs = citationStyleFromString(command);
248 vector<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.forceUpperCase);
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<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<CiteStyle> const & styles = citeStyles_;
455 if (styles[choice] == NOCITE) {
463 s.style = styles[choice];
465 s.forceUpperCase = force;
466 string const command = citationStyleToString(s);
468 params_.setCmdName(command);
469 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
470 params_["before"] = qstring_to_ucs4(before);
471 params_["after"] = qstring_to_ucs4(after);
476 void GuiCitation::clearSelection()
479 selected_model_.setStringList(cited_keys_);
483 QString GuiCitation::textBefore()
485 return toqstr(params_["before"]);
489 QString GuiCitation::textAfter()
491 return toqstr(params_["after"]);
495 void GuiCitation::init()
497 // Make the list of all available bibliography keys
498 all_keys_ = to_qstring_list(availableKeys());
499 available_model_.setStringList(all_keys_);
501 // Ditto for the keys cited in this inset
502 QString str = toqstr(params_["key"]);
506 cited_keys_ = str.split(",");
507 selected_model_.setStringList(cited_keys_);
511 void GuiCitation::findKey(QString const & str, bool only_keys,
512 docstring field, docstring entry_type,
513 bool case_sensitive, bool reg_exp, bool reset)
515 // Used for optimisation: store last searched string.
516 static QString last_searched_string;
517 // Used to disable the above optimisation.
518 static bool last_case_sensitive;
519 static bool last_reg_exp;
520 // Reset last_searched_string in case of changed option.
521 if (last_case_sensitive != case_sensitive
522 || last_reg_exp != reg_exp) {
523 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
524 last_searched_string.clear();
526 // save option for next search.
527 last_case_sensitive = case_sensitive;
528 last_reg_exp = reg_exp;
530 Qt::CaseSensitivity qtcase = case_sensitive?
531 Qt::CaseSensitive: Qt::CaseInsensitive;
533 // If new string (str) contains the last searched one...
535 !last_searched_string.isEmpty() &&
537 str.contains(last_searched_string, qtcase))
538 // ... then only search within already found list.
539 keys = available_model_.stringList();
541 // ... else search all keys.
543 // save searched string for next search.
544 last_searched_string = str;
548 // First, filter by entry_type, which will be faster than
549 // what follows, so we may get to do that on less.
550 vector<docstring> keyVector = to_docstring_vector(keys);
551 filterByEntryType(keyVector, entry_type);
554 result = to_qstring_list(keyVector);
556 result = to_qstring_list(searchKeys(keyVector, only_keys,
557 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
559 available_model_.setStringList(result);
563 QStringList GuiCitation::getFieldsAsQStringList()
565 return to_qstring_list(availableFields());
569 QStringList GuiCitation::getEntriesAsQStringList()
571 return to_qstring_list(availableEntries());
575 QStringList GuiCitation::citationStyles(int sel)
577 docstring const key = qstring_to_ucs4(cited_keys_[sel]);
578 return to_qstring_list(bibkeysInfo_.getCiteStrings(key, buffer()));
582 QString GuiCitation::getKeyInfo(QString const & sel)
584 return toqstr(getInfo(qstring_to_ucs4(sel)));
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 bibkeysInfo_.fillWithBibKeys(&buffer());
599 citeStyles_ = citeStyles(engine);
604 void GuiCitation::clearParams()
607 bibkeysInfo_.clear();
611 vector<docstring> GuiCitation::availableKeys() const
613 return bibkeysInfo_.getKeys();
617 vector<docstring> GuiCitation::availableFields() const
619 return bibkeysInfo_.getFields();
623 vector<docstring> GuiCitation::availableEntries() const
625 return bibkeysInfo_.getEntries();
629 void GuiCitation::filterByEntryType(
630 vector<docstring> & keyVector, docstring entry_type)
632 if (entry_type.empty())
635 vector<docstring>::iterator it = keyVector.begin();
636 vector<docstring>::iterator end = keyVector.end();
638 vector<docstring> result;
639 for (; it != end; ++it) {
640 docstring const key = *it;
641 BiblioInfo::const_iterator cit = bibkeysInfo_.find(key);
642 if (cit == bibkeysInfo_.end())
644 if (cit->second.entryType() == entry_type)
645 result.push_back(key);
651 CiteEngine GuiCitation::citeEngine() const
653 return buffer().params().citeEngine();
657 docstring GuiCitation::getInfo(docstring const & key) const
659 if (bibkeysInfo_.empty())
662 return bibkeysInfo_.getInfo(key);
666 // Escape special chars.
667 // All characters are literals except: '.|*?+(){}[]^$\'
668 // These characters are literals when preceded by a "\", which is done here
669 // @todo: This function should be moved to support, and then the test in tests
670 // should be moved there as well.
671 static docstring escape_special_chars(docstring const & expr)
673 // Search for all chars '.|*?+(){}[^$]\'
674 // Note that '[' and '\' must be escaped.
675 // This is a limitation of boost::regex, but all other chars in BREs
676 // are assumed literal.
677 static const boost::regex reg("[].|*?+(){}^$\\[\\\\]");
679 // $& is a perl-like expression that expands to all
680 // of the current match
681 // The '$' must be prefixed with the escape character '\' for
682 // boost to treat it as a literal.
683 // Thus, to prefix a matched expression with '\', we use:
685 return from_utf8(boost::regex_replace(to_utf8(expr), reg, "\\\\$&"));
689 vector<docstring> GuiCitation::searchKeys(
690 vector<docstring> const & keys_to_search, bool only_keys,
691 docstring const & search_expression, docstring field,
692 bool case_sensitive, bool regex)
694 vector<docstring> foundKeys;
696 docstring expr = trim(search_expression);
701 // We must escape special chars in the search_expr so that
702 // it is treated as a simple string by boost::regex.
703 expr = escape_special_chars(expr);
705 boost::regex reg_exp;
707 reg_exp.assign(to_utf8(expr), case_sensitive ?
708 boost::regex_constants::normal : boost::regex_constants::icase);
709 } catch (boost::regex_error & e) {
710 // boost::regex throws an exception if the regular expression is not
712 LYXERR(Debug::GUI, e.what());
713 return vector<docstring>();
716 vector<docstring>::const_iterator it = keys_to_search.begin();
717 vector<docstring>::const_iterator end = keys_to_search.end();
718 for (; it != end; ++it ) {
719 BiblioInfo::const_iterator info = bibkeysInfo_.find(*it);
720 if (info == bibkeysInfo_.end())
723 BibTeXInfo const & kvm = info->second;
727 else if (field.empty())
728 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
729 else if (kvm.hasField(field))
730 data = to_utf8(kvm.getValueForField(field));
736 if (boost::regex_search(data, reg_exp))
737 foundKeys.push_back(*it);
739 catch (boost::regex_error & e) {
740 LYXERR(Debug::GUI, e.what());
741 return vector<docstring>();
748 void GuiCitation::dispatchParams()
750 std::string const lfun = InsetCommand::params2string("citation", params_);
751 dispatch(FuncRequest(getLfun(), lfun));
755 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
758 } // namespace frontend
761 #include "GuiCitation_moc.cpp"