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(findLE, SIGNAL(returnPressed()),
96 this, SLOT(on_searchPB_clicked()));
97 connect(textBeforeED, SIGNAL(returnPressed()),
98 this, SLOT(on_okPB_clicked()));
99 connect(textAfterED, SIGNAL(returnPressed()),
100 this, SLOT(on_okPB_clicked()));
101 connect(this, SIGNAL(rejected()), this, SLOT(cleanUp()));
103 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
104 addPB, deletePB, upPB, downPB, available(), selected());
105 connect(selectionManager, SIGNAL(selectionChanged()),
106 this, SLOT(setCitedKeys()));
107 connect(selectionManager, SIGNAL(updateHook()),
108 this, SLOT(updateDialog()));
109 connect(selectionManager, SIGNAL(okHook()),
110 this, SLOT(on_okPB_clicked()));
112 bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
116 void GuiCitation::cleanUp()
124 void GuiCitation::closeEvent(QCloseEvent * e)
132 void GuiCitation::applyView()
134 int const choice = max(0, citationStyleCO->currentIndex());
136 bool const full = fulllistCB->isChecked();
137 bool const force = forceuppercaseCB->isChecked();
139 QString const before = textBeforeED->text();
140 QString const after = textAfterED->text();
142 apply(choice, full, force, before, after);
146 void GuiCitation::showEvent(QShowEvent * e)
150 availableLV->setFocus();
151 GuiDialog::showEvent(e);
155 void GuiCitation::on_okPB_clicked()
163 void GuiCitation::on_cancelPB_clicked()
170 void GuiCitation::on_applyPB_clicked()
176 void GuiCitation::on_restorePB_clicked()
183 void GuiCitation::updateView()
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::updateDialog()
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(textBefore());
214 textAfterED->setText(textAfter());
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()->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 = getFieldsAsQStringList();
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 = getEntriesAsQStringList();
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()->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)
359 QString const keytxt = getKeyInfo(idx.data().toString());
360 infoML->document()->setPlainText(keytxt);
362 infoML->document()->clear();
366 void GuiCitation::findText(QString const & text, bool reset)
368 //"All Fields" and "Keys" are the first two
369 int index = fieldsCO->currentIndex() - 2;
370 vector<docstring> const & fields = availableFields();
373 if (index <= -1 || index >= int(fields.size()))
374 //either "All Fields" or "Keys" or an invalid value
375 field = from_ascii("");
377 field = fields[index];
380 bool const onlyKeys = index == -1;
382 //"All Entry Types" is first.
383 index = entriesCO->currentIndex() - 1;
384 vector<docstring> const & entries = availableEntries();
385 docstring entry_type;
386 if (index < 0 || index >= int(entries.size()))
387 entry_type = from_ascii("");
389 entry_type = entries[index];
391 bool const case_sentitive = caseCB->checkState();
392 bool const reg_exp = regexCB->checkState();
393 findKey(text, onlyKeys, field, entry_type,
394 case_sentitive, reg_exp, reset);
396 //It'd be nice to save and restore the current selection in
397 //availableLV. Currently, we get an automatic reset, since the
404 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
406 findText(findLE->text(), true);
410 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
412 findText(findLE->text(), true);
416 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
418 if (index >= 0 && index < citationStyleCO->count()) {
419 vector<CiteStyle> const & styles = citeStyles_;
420 updateFormatting(styles[index]);
425 void GuiCitation::on_findLE_textChanged(const QString & text)
427 searchPB->setDisabled(text.isEmpty());
430 findText(findLE->text());
434 void GuiCitation::on_searchPB_clicked()
436 findText(findLE->text());
440 void GuiCitation::on_caseCB_stateChanged(int)
442 findText(findLE->text());
446 void GuiCitation::on_regexCB_stateChanged(int)
448 findText(findLE->text());
452 void GuiCitation::changed()
458 void GuiCitation::apply(int const choice, bool full, bool force,
459 QString before, QString after)
461 if (cited_keys_.isEmpty())
464 vector<CiteStyle> const & styles = citeStyles_;
465 if (styles[choice] == NOCITE) {
473 s.style = styles[choice];
475 s.forceUpperCase = force;
476 string const command = citationStyleToString(s);
478 params_.setCmdName(command);
479 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
480 params_["before"] = qstring_to_ucs4(before);
481 params_["after"] = qstring_to_ucs4(after);
486 void GuiCitation::clearSelection()
489 selected_model_.setStringList(cited_keys_);
493 QString GuiCitation::textBefore()
495 return toqstr(params_["before"]);
499 QString GuiCitation::textAfter()
501 return toqstr(params_["after"]);
505 void GuiCitation::init()
507 // Make the list of all available bibliography keys
508 all_keys_ = to_qstring_list(availableKeys());
509 available_model_.setStringList(all_keys_);
511 // Ditto for the keys cited in this inset
512 QString str = toqstr(params_["key"]);
516 cited_keys_ = str.split(",");
517 selected_model_.setStringList(cited_keys_);
521 void GuiCitation::findKey(QString const & str, bool only_keys,
522 docstring field, docstring entry_type,
523 bool case_sensitive, bool reg_exp, bool reset)
525 // Used for optimisation: store last searched string.
526 static QString last_searched_string;
527 // Used to disable the above optimisation.
528 static bool last_case_sensitive;
529 static bool last_reg_exp;
530 // Reset last_searched_string in case of changed option.
531 if (last_case_sensitive != case_sensitive
532 || last_reg_exp != reg_exp) {
533 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
534 last_searched_string.clear();
536 // save option for next search.
537 last_case_sensitive = case_sensitive;
538 last_reg_exp = reg_exp;
540 Qt::CaseSensitivity qtcase = case_sensitive ?
541 Qt::CaseSensitive: Qt::CaseInsensitive;
543 // If new string (str) contains the last searched one...
545 !last_searched_string.isEmpty() &&
547 str.contains(last_searched_string, qtcase))
548 // ... then only search within already found list.
549 keys = available_model_.stringList();
551 // ... else search all keys.
553 // save searched string for next search.
554 last_searched_string = str;
558 // First, filter by entry_type, which will be faster than
559 // what follows, so we may get to do that on less.
560 vector<docstring> keyVector = to_docstring_vector(keys);
561 filterByEntryType(keyVector, entry_type);
564 result = to_qstring_list(keyVector);
566 result = to_qstring_list(searchKeys(keyVector, only_keys,
567 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
569 available_model_.setStringList(result);
573 QStringList GuiCitation::getFieldsAsQStringList()
575 return to_qstring_list(availableFields());
579 QStringList GuiCitation::getEntriesAsQStringList()
581 return to_qstring_list(availableEntries());
585 QStringList GuiCitation::citationStyles(int sel)
587 docstring const key = qstring_to_ucs4(cited_keys_[sel]);
588 return to_qstring_list(bibkeysInfo_.getCiteStrings(key, buffer()));
592 QString GuiCitation::getKeyInfo(QString const & sel)
594 return toqstr(getInfo(qstring_to_ucs4(sel)));
598 void GuiCitation::setCitedKeys()
600 cited_keys_ = selected_model_.stringList();
604 bool GuiCitation::initialiseParams(string const & data)
606 InsetCommand::string2params("citation", data, params_);
607 CiteEngine const engine = buffer().params().citeEngine();
608 bibkeysInfo_.fillWithBibKeys(&buffer());
609 citeStyles_ = citeStyles(engine);
614 void GuiCitation::clearParams()
617 bibkeysInfo_.clear();
621 vector<docstring> GuiCitation::availableKeys() const
623 return bibkeysInfo_.getKeys();
627 vector<docstring> GuiCitation::availableFields() const
629 return bibkeysInfo_.getFields();
633 vector<docstring> GuiCitation::availableEntries() const
635 return bibkeysInfo_.getEntries();
639 void GuiCitation::filterByEntryType(
640 vector<docstring> & keyVector, docstring entry_type)
642 if (entry_type.empty())
645 vector<docstring>::iterator it = keyVector.begin();
646 vector<docstring>::iterator end = keyVector.end();
648 vector<docstring> result;
649 for (; it != end; ++it) {
650 docstring const key = *it;
651 BiblioInfo::const_iterator cit = bibkeysInfo_.find(key);
652 if (cit == bibkeysInfo_.end())
654 if (cit->second.entryType() == entry_type)
655 result.push_back(key);
661 CiteEngine GuiCitation::citeEngine() const
663 return buffer().params().citeEngine();
667 docstring GuiCitation::getInfo(docstring const & key) const
669 if (bibkeysInfo_.empty())
672 return bibkeysInfo_.getInfo(key);
676 // Escape special chars.
677 // All characters are literals except: '.|*?+(){}[]^$\'
678 // These characters are literals when preceded by a "\", which is done here
679 // @todo: This function should be moved to support, and then the test in tests
680 // should be moved there as well.
681 static docstring escape_special_chars(docstring const & expr)
683 // Search for all chars '.|*?+(){}[^$]\'
684 // Note that '[' and '\' must be escaped.
685 // This is a limitation of boost::regex, but all other chars in BREs
686 // are assumed literal.
687 static const boost::regex reg("[].|*?+(){}^$\\[\\\\]");
689 // $& is a perl-like expression that expands to all
690 // of the current match
691 // The '$' must be prefixed with the escape character '\' for
692 // boost to treat it as a literal.
693 // Thus, to prefix a matched expression with '\', we use:
695 return from_utf8(boost::regex_replace(to_utf8(expr), reg, "\\\\$&"));
699 vector<docstring> GuiCitation::searchKeys(
700 vector<docstring> const & keys_to_search, bool only_keys,
701 docstring const & search_expression, docstring field,
702 bool case_sensitive, bool regex)
704 vector<docstring> foundKeys;
706 docstring expr = trim(search_expression);
711 // We must escape special chars in the search_expr so that
712 // it is treated as a simple string by boost::regex.
713 expr = escape_special_chars(expr);
715 boost::regex reg_exp;
717 reg_exp.assign(to_utf8(expr), case_sensitive ?
718 boost::regex_constants::normal : boost::regex_constants::icase);
719 } catch (boost::regex_error & e) {
720 // boost::regex throws an exception if the regular expression is not
722 LYXERR(Debug::GUI, e.what());
723 return vector<docstring>();
726 vector<docstring>::const_iterator it = keys_to_search.begin();
727 vector<docstring>::const_iterator end = keys_to_search.end();
728 for (; it != end; ++it ) {
729 BiblioInfo::const_iterator info = bibkeysInfo_.find(*it);
730 if (info == bibkeysInfo_.end())
733 BibTeXInfo const & kvm = info->second;
737 else if (field.empty())
738 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
739 else if (kvm.hasField(field))
740 data = to_utf8(kvm.getValueForField(field));
746 if (boost::regex_search(data, reg_exp))
747 foundKeys.push_back(*it);
749 catch (boost::regex_error & e) {
750 LYXERR(Debug::GUI, e.what());
751 return vector<docstring>();
758 void GuiCitation::dispatchParams()
760 std::string const lfun = InsetCommand::params2string("citation", params_);
761 dispatch(FuncRequest(getLfun(), lfun));
765 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
768 } // namespace frontend
771 #include "GuiCitation_moc.cpp"