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 "GuiApplication.h"
20 #include "GuiSelectionManager.h"
21 #include "LyXToolBox.h"
22 #include "qt_helpers.h"
25 #include "BufferView.h"
26 #include "BiblioInfo.h"
27 #include "BufferParams.h"
28 #include "TextClass.h"
29 #include "FuncRequest.h"
31 #include "insets/InsetCommand.h"
33 #include "support/debug.h"
34 #include "support/docstring.h"
35 #include "support/gettext.h"
36 #include "support/lstrings.h"
38 #include <QCloseEvent>
49 #include "support/regex.h"
56 using namespace lyx::support;
62 // I am guessing that it would not hurt to make these private members.
63 static vector<string> citeCmds_;
64 static vector<CitationStyle> citeStyles_;
67 template<typename String>
68 static QStringList to_qstring_list(vector<String> const & v)
72 for (size_t i = 0; i != v.size(); ++i) {
75 qlist.append(lyx::toqstr(v[i]));
81 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
83 vector<lyx::docstring> v;
84 for (int i = 0; i != qlist.size(); ++i) {
85 if (qlist[i].isEmpty())
87 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
93 GuiCitation::GuiCitation(GuiView & lv)
94 : DialogView(lv, "citation", qt_("Citation")),
95 style_(0), params_(insetCode("citation"))
100 filter_ = new FancyLineEdit(this);
101 filter_->setButtonPixmap(FancyLineEdit::Right, getPixmap("images/", "editclear", "svgz,png"));
102 filter_->setButtonVisible(FancyLineEdit::Right, true);
103 filter_->setButtonToolTip(FancyLineEdit::Right, qt_("Clear text"));
104 filter_->setAutoHideButton(FancyLineEdit::Right, true);
105 filter_->setPlaceholderText(qt_("All avail. citations"));
107 filterBarL->addWidget(filter_, 0);
108 findKeysLA->setBuddy(filter_);
110 // Add search options as button menu
111 regexp_ = new QAction(qt_("Regular e&xpression"), this);
112 regexp_->setCheckable(true);
113 casesense_ = new QAction(qt_("Case se&nsitive"), this);
114 casesense_->setCheckable(true);
115 instant_ = new QAction(qt_("Search as you &type"), this);
116 instant_->setCheckable(true);
117 instant_->setChecked(true);
119 QMenu * searchOpts = new QMenu(this);
120 searchOpts->addAction(regexp_);
121 searchOpts->addAction(casesense_);
122 searchOpts->addAction(instant_);
123 searchOptionsPB->setMenu(searchOpts);
125 connect(citationStyleCO, SIGNAL(activated(int)),
126 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
127 connect(starredCB, SIGNAL(clicked()),
128 this, SLOT(updateStyles()));
129 connect(forceuppercaseCB, SIGNAL(clicked()),
130 this, SLOT(updateStyles()));
131 connect(textBeforeED, SIGNAL(textChanged(QString)),
132 this, SLOT(updateStyles()));
133 connect(textAfterED, SIGNAL(textChanged(QString)),
134 this, SLOT(updateStyles()));
135 connect(textBeforeED, SIGNAL(returnPressed()),
136 this, SLOT(on_okPB_clicked()));
137 connect(textAfterED, SIGNAL(returnPressed()),
138 this, SLOT(on_okPB_clicked()));
140 selectionManager = new GuiSelectionManager(availableLV, selectedLV,
141 addPB, deletePB, upPB, downPB, &available_model_, &selected_model_);
142 connect(selectionManager, SIGNAL(selectionChanged()),
143 this, SLOT(setCitedKeys()));
144 connect(selectionManager, SIGNAL(updateHook()),
145 this, SLOT(updateControls()));
146 connect(selectionManager, SIGNAL(okHook()),
147 this, SLOT(on_okPB_clicked()));
149 connect(filter_, SIGNAL(rightButtonClicked()),
150 this, SLOT(resetFilter()));
151 connect(filter_, SIGNAL(textEdited(QString)),
152 this, SLOT(filterChanged(QString)));
153 connect(filter_, SIGNAL(returnPressed()),
154 this, SLOT(filterPressed()));
155 connect(regexp_, SIGNAL(triggered()),
156 this, SLOT(regexChanged()));
157 connect(casesense_, SIGNAL(triggered()),
158 this, SLOT(caseChanged()));
159 connect(instant_, SIGNAL(triggered(bool)),
160 this, SLOT(instantChanged(bool)));
162 setFocusProxy(filter_);
166 GuiCitation::~GuiCitation()
168 delete selectionManager;
172 void GuiCitation::closeEvent(QCloseEvent * e)
175 DialogView::closeEvent(e);
179 void GuiCitation::applyView()
181 int const choice = max(0, citationStyleCO->currentIndex());
183 bool const full = starredCB->isChecked();
184 bool const force = forceuppercaseCB->isChecked();
186 QString const before = textBeforeED->text();
187 QString const after = textAfterED->text();
189 applyParams(choice, full, force, before, after);
193 void GuiCitation::showEvent(QShowEvent * e)
196 availableLV->setFocus();
197 DialogView::showEvent(e);
201 void GuiCitation::on_okPB_clicked()
209 void GuiCitation::on_cancelPB_clicked()
216 void GuiCitation::on_applyPB_clicked()
222 void GuiCitation::on_restorePB_clicked()
229 void GuiCitation::updateControls()
231 BiblioInfo const & bi = bibInfo();
236 // The main point of separating this out is that the fill*() methods
237 // called in update() do not need to be called for INTERNAL updates,
238 // such as when addPB is pressed, as the list of fields, entries, etc,
239 // will not have changed.
240 void GuiCitation::updateControls(BiblioInfo const & bi)
242 QModelIndex idx = selectionManager->getSelectedIndex();
244 selectionManager->update();
248 void GuiCitation::updateFormatting(CitationStyle currentStyle)
250 BufferParams const bp = documentBuffer().params();
251 bool const force = currentStyle.forceUpperCase;
252 bool const starred = currentStyle.hasStarredVersion;
253 bool const full = starred && bp.fullAuthorList();
254 bool const textbefore = currentStyle.textBefore;
255 bool const textafter = currentStyle.textAfter;
257 bool const haveSelection =
258 selectedLV->model()->rowCount() > 0;
260 forceuppercaseCB->setEnabled(force && haveSelection);
261 starredCB->setEnabled(full && haveSelection);
262 textBeforeED->setEnabled(textbefore && haveSelection);
263 textBeforeLA->setEnabled(textbefore && haveSelection);
264 textAfterED->setEnabled(textafter && haveSelection);
265 textAfterLA->setEnabled(textafter && haveSelection);
266 citationStyleCO->setEnabled(haveSelection);
267 citationStyleLA->setEnabled(haveSelection);
269 // Check if we have a custom string/tooltip for the starred version
270 if (starred && !currentStyle.stardesc.empty()) {
272 bp.documentClass().getCiteMacro(bp.citeEngineType(), currentStyle.stardesc);
275 guistring = translateIfPossible(from_utf8(val));
276 starredCB->setText(toqstr(guistring));
277 starredCB->setEnabled(haveSelection);
279 if (!currentStyle.startooltip.empty()) {
280 val = bp.documentClass().getCiteMacro(bp.citeEngineType(),
281 currentStyle.startooltip);
283 guistring = translateIfPossible(from_utf8(val));
285 // Tooltip might also be empty
286 starredCB->setToolTip(toqstr(guistring));
288 // This is the default meaning of the starred commands
289 starredCB->setText(qt_("All aut&hors"));
290 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\")"));
295 // Update the styles for the style combo, citationStyleCO, and mark the
296 // settings as changed. Called upon changing the cited keys (including
297 // merely reordering the keys) or editing the text before/after fields.
298 void GuiCitation::updateStyles()
300 BiblioInfo const & bi = bibInfo();
306 // Update the styles for the style combo, citationStyleCO.
307 void GuiCitation::updateStyles(BiblioInfo const & bi)
309 QStringList selected_keys = selected_model_.stringList();
310 int curr = selectedLV->model()->rowCount() - 1;
312 if (curr < 0 || selected_keys.empty()) {
313 citationStyleCO->clear();
314 citationStyleCO->setEnabled(false);
315 citationStyleLA->setEnabled(false);
319 static const size_t max_length = 80;
320 QStringList sty = citationStyles(bi, max_length);
324 citationStyleCO->setEnabled(false);
325 citationStyleLA->setEnabled(false);
326 citationStyleCO->clear();
330 citationStyleCO->blockSignals(true);
333 int const curindex = citationStyleCO->currentIndex();
334 int const oldIndex = (curindex < 0) ? style_ : curindex;
335 citationStyleCO->clear();
336 citationStyleCO->insertItems(0, sty);
337 citationStyleCO->setEnabled(true);
338 citationStyleLA->setEnabled(true);
340 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
341 citationStyleCO->setCurrentIndex(oldIndex);
343 citationStyleCO->blockSignals(false);
347 void GuiCitation::fillFields(BiblioInfo const & bi)
349 fieldsCO->blockSignals(true);
350 int const oldIndex = fieldsCO->currentIndex();
352 QStringList const fields = to_qstring_list(bi.getFields());
353 fieldsCO->insertItem(0, qt_("All fields"));
354 fieldsCO->insertItem(1, qt_("Keys"));
355 fieldsCO->insertItems(2, fields);
356 if (oldIndex != -1 && oldIndex < fieldsCO->count())
357 fieldsCO->setCurrentIndex(oldIndex);
358 fieldsCO->blockSignals(false);
362 void GuiCitation::fillEntries(BiblioInfo const & bi)
364 entriesCO->blockSignals(true);
365 int const oldIndex = entriesCO->currentIndex();
367 QStringList const entries = to_qstring_list(bi.getEntries());
368 entriesCO->insertItem(0, qt_("All entry types"));
369 entriesCO->insertItems(1, entries);
370 if (oldIndex != -1 && oldIndex < entriesCO->count())
371 entriesCO->setCurrentIndex(oldIndex);
372 entriesCO->blockSignals(false);
376 bool GuiCitation::isSelected(QModelIndex const & idx)
378 QString const str = idx.data().toString();
379 return selected_model_.stringList().contains(str);
383 void GuiCitation::setButtons()
385 int const srows = selectedLV->model()->rowCount();
386 applyPB->setEnabled(srows > 0);
387 okPB->setEnabled(srows > 0);
391 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
393 if (!idx.isValid() || bi.empty()) {
394 infoML->document()->clear();
395 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
399 infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
402 QString const keytxt = toqstr(
403 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), ci));
404 infoML->document()->setHtml(keytxt);
408 void GuiCitation::findText(QString const & text, bool reset)
410 //"All Fields" and "Keys" are the first two
411 int index = fieldsCO->currentIndex() - 2;
412 BiblioInfo const & bi = bibInfo();
413 vector<docstring> const & fields = bi.getFields();
416 if (index <= -1 || index >= int(fields.size()))
417 //either "All Fields" or "Keys" or an invalid value
418 field = from_ascii("");
420 field = fields[index];
423 bool const onlyKeys = index == -1;
425 //"All Entry Types" is first.
426 index = entriesCO->currentIndex() - 1;
427 vector<docstring> const & entries = bi.getEntries();
428 docstring entry_type;
429 if (index < 0 || index >= int(entries.size()))
430 entry_type = from_ascii("");
432 entry_type = entries[index];
434 bool const case_sentitive = casesense_->isChecked();
435 bool const reg_exp = regexp_->isChecked();
437 findKey(bi, text, onlyKeys, field, entry_type,
438 case_sentitive, reg_exp, reset);
440 //It'd be nice to save and restore the current selection in
441 //availableLV. Currently, we get an automatic reset, since the
448 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
450 findText(filter_->text(), true);
454 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
456 findText(filter_->text(), true);
460 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
462 if (index >= 0 && index < citationStyleCO->count()) {
463 vector<CitationStyle> const & styles = citeStyles_;
464 updateFormatting(styles[index]);
470 void GuiCitation::filterChanged(const QString & text)
472 if (!text.isEmpty()) {
473 if (instant_->isChecked())
474 findText(filter_->text());
477 findText(filter_->text());
482 void GuiCitation::filterPressed()
484 findText(filter_->text(), true);
488 void GuiCitation::resetFilter()
490 filter_->setText(QString());
491 findText(filter_->text(), true);
495 void GuiCitation::caseChanged()
497 findText(filter_->text());
501 void GuiCitation::regexChanged()
503 findText(filter_->text());
507 void GuiCitation::updateFilterHint()
509 QString const hint = instant_->isChecked() ?
510 qt_("Enter string to filter the list of available citations") :
511 qt_("Enter string to filter the list of available citations and press <Enter>");
512 filter_->setToolTip(hint);
516 void GuiCitation::instantChanged(bool checked)
519 findText(filter_->text(), true);
525 void GuiCitation::changed()
531 void GuiCitation::applyParams(int const choice, bool full, bool force,
532 QString before, QString after)
534 if (cited_keys_.isEmpty())
537 vector<CitationStyle> const & styles = citeStyles_;
539 CitationStyle cs = styles[choice];
546 cs.forceUpperCase &= force;
547 cs.hasStarredVersion &= full;
548 string const command = citationStyleToString(cs);
550 params_.setCmdName(command);
551 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
552 params_["before"] = qstring_to_ucs4(before);
553 params_["after"] = qstring_to_ucs4(after);
558 void GuiCitation::clearSelection()
561 selected_model_.setStringList(cited_keys_);
565 void GuiCitation::init()
567 // Make the list of all available bibliography keys
568 BiblioInfo const & bi = bibInfo();
569 all_keys_ = to_qstring_list(bi.getKeys());
570 available_model_.setStringList(all_keys_);
572 // Ditto for the keys cited in this inset
573 QString str = toqstr(params_["key"]);
577 cited_keys_ = str.split(",");
578 selected_model_.setStringList(cited_keys_);
580 // Initialize the drop downs
584 // Initialize the citation formatting
585 string const & cmd = params_.getCmdName();
586 CitationStyle const cs =
587 citationStyleFromString(cmd, documentBuffer().params());
588 forceuppercaseCB->setChecked(cs.forceUpperCase);
589 starredCB->setChecked(cs.hasStarredVersion &&
590 documentBuffer().params().fullAuthorList());
591 textBeforeED->setText(toqstr(params_["before"]));
592 textAfterED->setText(toqstr(params_["after"]));
594 // Update the interface
597 if (selected_model_.rowCount()) {
598 selectedLV->blockSignals(true);
599 selectedLV->setFocus();
600 QModelIndex idx = selected_model_.index(0, 0);
601 selectedLV->selectionModel()->select(idx,
602 QItemSelectionModel::ClearAndSelect);
603 selectedLV->blockSignals(false);
605 // Find the citation style
606 vector<string> const & cmds = citeCmds_;
607 vector<string>::const_iterator cit =
608 std::find(cmds.begin(), cmds.end(), cs.name);
610 if (cit != cmds.end())
611 i = int(cit - cmds.begin());
613 // Set the style combo appropriately
614 citationStyleCO->blockSignals(true);
615 citationStyleCO->setCurrentIndex(i);
616 citationStyleCO->blockSignals(false);
617 updateFormatting(citeStyles_[i]);
619 availableLV->setFocus();
621 applyPB->setEnabled(false);
622 okPB->setEnabled(false);
626 void GuiCitation::findKey(BiblioInfo const & bi,
627 QString const & str, bool only_keys,
628 docstring field, docstring entry_type,
629 bool case_sensitive, bool reg_exp, bool reset)
632 // This should be moved to a class member.
633 // Used for optimisation: store last searched string.
634 static QString last_searched_string;
635 // Used to disable the above optimisation.
636 static bool last_case_sensitive;
637 static bool last_reg_exp;
638 // Reset last_searched_string in case of changed option.
639 if (last_case_sensitive != case_sensitive
640 || last_reg_exp != reg_exp) {
641 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
642 last_searched_string.clear();
644 // save option for next search.
645 last_case_sensitive = case_sensitive;
646 last_reg_exp = reg_exp;
648 Qt::CaseSensitivity qtcase = case_sensitive ?
649 Qt::CaseSensitive: Qt::CaseInsensitive;
651 // If new string (str) contains the last searched one...
653 !last_searched_string.isEmpty() &&
655 str.contains(last_searched_string, qtcase))
656 // ... then only search within already found list.
657 keys = available_model_.stringList();
659 // ... else search all keys.
661 // save searched string for next search.
662 last_searched_string = str;
666 // First, filter by entry_type, which will be faster than
667 // what follows, so we may get to do that on less.
668 vector<docstring> keyVector = to_docstring_vector(keys);
669 filterByEntryType(bi, keyVector, entry_type);
672 result = to_qstring_list(keyVector);
674 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
675 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
677 available_model_.setStringList(result);
681 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
683 vector<docstring> const keys = to_docstring_vector(cited_keys_);
684 vector<CitationStyle> styles = citeStyles_;
686 ci.textBefore = qstring_to_ucs4(textBeforeED->text());
687 ci.textAfter = qstring_to_ucs4(textAfterED->text());
688 ci.forceUpperCase = forceuppercaseCB->isChecked();
689 ci.Starred = starredCB->isChecked();
690 ci.context = CiteItem::Dialog;
691 ci.max_size = max_size;
692 vector<docstring> ret = bi.getCiteStrings(keys, styles, documentBuffer(), ci);
693 return to_qstring_list(ret);
697 void GuiCitation::setCitedKeys()
699 cited_keys_ = selected_model_.stringList();
704 bool GuiCitation::initialiseParams(string const & data)
706 InsetCommand::string2params(data, params_);
707 citeCmds_ = documentBuffer().params().citeCommands();
708 citeStyles_ = documentBuffer().params().citeStyles();
714 void GuiCitation::clearParams()
720 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
721 vector<docstring> & keyVector, docstring entry_type)
723 if (entry_type.empty())
726 vector<docstring>::iterator it = keyVector.begin();
727 vector<docstring>::iterator end = keyVector.end();
729 vector<docstring> result;
730 for (; it != end; ++it) {
731 docstring const key = *it;
732 BiblioInfo::const_iterator cit = bi.find(key);
735 if (cit->second.entryType() == entry_type)
736 result.push_back(key);
742 // Escape special chars.
743 // All characters are literals except: '.|*?+(){}[]^$\'
744 // These characters are literals when preceded by a "\", which is done here
745 // @todo: This function should be moved to support, and then the test in tests
746 // should be moved there as well.
747 static docstring escape_special_chars(docstring const & expr)
749 // Search for all chars '.|*?+(){}[^$]\'
750 // Note that '[', ']', and '\' must be escaped.
751 static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
753 // $& is an ECMAScript format expression that expands to all
754 // of the current match
755 #ifdef LYX_USE_STD_REGEX
756 // To prefix a matched expression with a single literal backslash, we
757 // need to escape it for the C++ compiler and use:
759 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
761 // A backslash in the format string starts an escape sequence in boost.
762 // Thus, to prefix a matched expression with a single literal backslash,
763 // we need to give two backslashes to the regex engine, and escape both
764 // for the C++ compiler and use:
766 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
771 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
772 vector<docstring> const & keys_to_search, bool only_keys,
773 docstring const & search_expression, docstring field,
774 bool case_sensitive, bool regex)
776 vector<docstring> foundKeys;
778 docstring expr = trim(search_expression);
783 // We must escape special chars in the search_expr so that
784 // it is treated as a simple string by lyx::regex.
785 expr = escape_special_chars(expr);
789 reg_exp.assign(to_utf8(expr), case_sensitive ?
790 lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
791 } catch (lyx::regex_error const & e) {
792 // lyx::regex throws an exception if the regular expression is not
794 LYXERR(Debug::GUI, e.what());
795 return vector<docstring>();
798 vector<docstring>::const_iterator it = keys_to_search.begin();
799 vector<docstring>::const_iterator end = keys_to_search.end();
800 for (; it != end; ++it ) {
801 BiblioInfo::const_iterator info = bi.find(*it);
802 if (info == bi.end())
805 BibTeXInfo const & kvm = info->second;
809 else if (field.empty())
810 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
812 data = to_utf8(kvm[field]);
818 if (lyx::regex_search(data, reg_exp))
819 foundKeys.push_back(*it);
821 catch (lyx::regex_error const & e) {
822 LYXERR(Debug::GUI, e.what());
823 return vector<docstring>();
830 void GuiCitation::dispatchParams()
832 std::string const lfun = InsetCommand::params2string(params_);
833 dispatch(FuncRequest(getLfun(), lfun));
837 BiblioInfo const & GuiCitation::bibInfo() const
839 Buffer const & buf = documentBuffer();
840 buf.reloadBibInfoCache();
841 return buf.masterBibInfo();
845 void GuiCitation::saveSession() const
847 Dialog::saveSession();
850 sessionKey() + "/regex", regexp_->isChecked());
852 sessionKey() + "/casesensitive", casesense_->isChecked());
854 sessionKey() + "/autofind", instant_->isChecked());
856 sessionKey() + "/citestyle", style_);
860 void GuiCitation::restoreSession()
862 Dialog::restoreSession();
864 regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
865 casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
866 instant_->setChecked(settings.value(sessionKey() + "/autofind").toBool());
867 style_ = settings.value(sessionKey() + "/citestyle").toInt();
872 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
875 } // namespace frontend
878 #include "moc_GuiCitation.cpp"