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(changed()));
129 connect(forceuppercaseCB, SIGNAL(clicked()),
130 this, SLOT(changed()));
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"));
400 QString const keytxt = toqstr(
401 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), true));
402 infoML->document()->setHtml(keytxt);
406 void GuiCitation::findText(QString const & text, bool reset)
408 //"All Fields" and "Keys" are the first two
409 int index = fieldsCO->currentIndex() - 2;
410 BiblioInfo const & bi = bibInfo();
411 vector<docstring> const & fields = bi.getFields();
414 if (index <= -1 || index >= int(fields.size()))
415 //either "All Fields" or "Keys" or an invalid value
416 field = from_ascii("");
418 field = fields[index];
421 bool const onlyKeys = index == -1;
423 //"All Entry Types" is first.
424 index = entriesCO->currentIndex() - 1;
425 vector<docstring> const & entries = bi.getEntries();
426 docstring entry_type;
427 if (index < 0 || index >= int(entries.size()))
428 entry_type = from_ascii("");
430 entry_type = entries[index];
432 bool const case_sentitive = casesense_->isChecked();
433 bool const reg_exp = regexp_->isChecked();
435 findKey(bi, text, onlyKeys, field, entry_type,
436 case_sentitive, reg_exp, reset);
438 //It'd be nice to save and restore the current selection in
439 //availableLV. Currently, we get an automatic reset, since the
446 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
448 findText(filter_->text(), true);
452 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
454 findText(filter_->text(), true);
458 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
460 if (index >= 0 && index < citationStyleCO->count()) {
461 vector<CitationStyle> const & styles = citeStyles_;
462 updateFormatting(styles[index]);
468 void GuiCitation::filterChanged(const QString & text)
470 if (!text.isEmpty()) {
471 if (instant_->isChecked())
472 findText(filter_->text());
475 findText(filter_->text());
480 void GuiCitation::filterPressed()
482 findText(filter_->text(), true);
486 void GuiCitation::resetFilter()
488 filter_->setText(QString());
489 findText(filter_->text(), true);
493 void GuiCitation::caseChanged()
495 findText(filter_->text());
499 void GuiCitation::regexChanged()
501 findText(filter_->text());
505 void GuiCitation::updateFilterHint()
507 QString const hint = instant_->isChecked() ?
508 qt_("Enter string to filter the list of available citations") :
509 qt_("Enter string to filter the list of available citations and press <Enter>");
510 filter_->setToolTip(hint);
514 void GuiCitation::instantChanged(bool checked)
517 findText(filter_->text(), true);
523 void GuiCitation::changed()
529 void GuiCitation::applyParams(int const choice, bool full, bool force,
530 QString before, QString after)
532 if (cited_keys_.isEmpty())
535 vector<CitationStyle> const & styles = citeStyles_;
537 CitationStyle cs = styles[choice];
544 cs.forceUpperCase &= force;
545 cs.hasStarredVersion &= full;
546 string const command = citationStyleToString(cs);
548 params_.setCmdName(command);
549 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
550 params_["before"] = qstring_to_ucs4(before);
551 params_["after"] = qstring_to_ucs4(after);
556 void GuiCitation::clearSelection()
559 selected_model_.setStringList(cited_keys_);
563 void GuiCitation::init()
565 // Make the list of all available bibliography keys
566 BiblioInfo const & bi = bibInfo();
567 all_keys_ = to_qstring_list(bi.getKeys());
568 available_model_.setStringList(all_keys_);
570 // Ditto for the keys cited in this inset
571 QString str = toqstr(params_["key"]);
575 cited_keys_ = str.split(",");
576 selected_model_.setStringList(cited_keys_);
578 // Initialize the drop downs
582 // Initialize the citation formatting
583 string const & cmd = params_.getCmdName();
584 CitationStyle const cs =
585 citationStyleFromString(cmd, documentBuffer().params());
586 forceuppercaseCB->setChecked(cs.forceUpperCase);
587 starredCB->setChecked(cs.hasStarredVersion &&
588 documentBuffer().params().fullAuthorList());
589 textBeforeED->setText(toqstr(params_["before"]));
590 textAfterED->setText(toqstr(params_["after"]));
592 // Update the interface
595 if (selected_model_.rowCount()) {
596 selectedLV->blockSignals(true);
597 selectedLV->setFocus();
598 QModelIndex idx = selected_model_.index(0, 0);
599 selectedLV->selectionModel()->select(idx,
600 QItemSelectionModel::ClearAndSelect);
601 selectedLV->blockSignals(false);
603 // Find the citation style
604 vector<string> const & cmds = citeCmds_;
605 vector<string>::const_iterator cit =
606 std::find(cmds.begin(), cmds.end(), cs.name);
608 if (cit != cmds.end())
609 i = int(cit - cmds.begin());
611 // Set the style combo appropriately
612 citationStyleCO->blockSignals(true);
613 citationStyleCO->setCurrentIndex(i);
614 citationStyleCO->blockSignals(false);
615 updateFormatting(citeStyles_[i]);
617 availableLV->setFocus();
619 applyPB->setEnabled(false);
620 okPB->setEnabled(false);
624 void GuiCitation::findKey(BiblioInfo const & bi,
625 QString const & str, bool only_keys,
626 docstring field, docstring entry_type,
627 bool case_sensitive, bool reg_exp, bool reset)
630 // This should be moved to a class member.
631 // Used for optimisation: store last searched string.
632 static QString last_searched_string;
633 // Used to disable the above optimisation.
634 static bool last_case_sensitive;
635 static bool last_reg_exp;
636 // Reset last_searched_string in case of changed option.
637 if (last_case_sensitive != case_sensitive
638 || last_reg_exp != reg_exp) {
639 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
640 last_searched_string.clear();
642 // save option for next search.
643 last_case_sensitive = case_sensitive;
644 last_reg_exp = reg_exp;
646 Qt::CaseSensitivity qtcase = case_sensitive ?
647 Qt::CaseSensitive: Qt::CaseInsensitive;
649 // If new string (str) contains the last searched one...
651 !last_searched_string.isEmpty() &&
653 str.contains(last_searched_string, qtcase))
654 // ... then only search within already found list.
655 keys = available_model_.stringList();
657 // ... else search all keys.
659 // save searched string for next search.
660 last_searched_string = str;
664 // First, filter by entry_type, which will be faster than
665 // what follows, so we may get to do that on less.
666 vector<docstring> keyVector = to_docstring_vector(keys);
667 filterByEntryType(bi, keyVector, entry_type);
670 result = to_qstring_list(keyVector);
672 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
673 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
675 available_model_.setStringList(result);
679 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
681 docstring const before = qstring_to_ucs4(textBeforeED->text());
682 docstring const after = qstring_to_ucs4(textAfterED->text());
683 vector<docstring> const keys = to_docstring_vector(cited_keys_);
684 vector<CitationStyle> styles = citeStyles_;
685 // FIXME: pass a dictionary instead of individual before, after, dialog, etc.
686 vector<docstring> ret = bi.getCiteStrings(keys, styles, documentBuffer(),
687 before, after, from_utf8("dialog"), max_size);
688 return to_qstring_list(ret);
692 void GuiCitation::setCitedKeys()
694 cited_keys_ = selected_model_.stringList();
699 bool GuiCitation::initialiseParams(string const & data)
701 InsetCommand::string2params(data, params_);
702 citeCmds_ = documentBuffer().params().citeCommands();
703 citeStyles_ = documentBuffer().params().citeStyles();
709 void GuiCitation::clearParams()
715 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
716 vector<docstring> & keyVector, docstring entry_type)
718 if (entry_type.empty())
721 vector<docstring>::iterator it = keyVector.begin();
722 vector<docstring>::iterator end = keyVector.end();
724 vector<docstring> result;
725 for (; it != end; ++it) {
726 docstring const key = *it;
727 BiblioInfo::const_iterator cit = bi.find(key);
730 if (cit->second.entryType() == entry_type)
731 result.push_back(key);
737 // Escape special chars.
738 // All characters are literals except: '.|*?+(){}[]^$\'
739 // These characters are literals when preceded by a "\", which is done here
740 // @todo: This function should be moved to support, and then the test in tests
741 // should be moved there as well.
742 static docstring escape_special_chars(docstring const & expr)
744 // Search for all chars '.|*?+(){}[^$]\'
745 // Note that '[', ']', and '\' must be escaped.
746 static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
748 // $& is an ECMAScript format expression that expands to all
749 // of the current match
750 #ifdef LYX_USE_STD_REGEX
751 // To prefix a matched expression with a single literal backslash, we
752 // need to escape it for the C++ compiler and use:
754 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
756 // A backslash in the format string starts an escape sequence in boost.
757 // Thus, to prefix a matched expression with a single literal backslash,
758 // we need to give two backslashes to the regex engine, and escape both
759 // for the C++ compiler and use:
761 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
766 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
767 vector<docstring> const & keys_to_search, bool only_keys,
768 docstring const & search_expression, docstring field,
769 bool case_sensitive, bool regex)
771 vector<docstring> foundKeys;
773 docstring expr = trim(search_expression);
778 // We must escape special chars in the search_expr so that
779 // it is treated as a simple string by lyx::regex.
780 expr = escape_special_chars(expr);
784 reg_exp.assign(to_utf8(expr), case_sensitive ?
785 lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
786 } catch (lyx::regex_error const & e) {
787 // lyx::regex throws an exception if the regular expression is not
789 LYXERR(Debug::GUI, e.what());
790 return vector<docstring>();
793 vector<docstring>::const_iterator it = keys_to_search.begin();
794 vector<docstring>::const_iterator end = keys_to_search.end();
795 for (; it != end; ++it ) {
796 BiblioInfo::const_iterator info = bi.find(*it);
797 if (info == bi.end())
800 BibTeXInfo const & kvm = info->second;
804 else if (field.empty())
805 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
807 data = to_utf8(kvm[field]);
813 if (lyx::regex_search(data, reg_exp))
814 foundKeys.push_back(*it);
816 catch (lyx::regex_error const & e) {
817 LYXERR(Debug::GUI, e.what());
818 return vector<docstring>();
825 void GuiCitation::dispatchParams()
827 std::string const lfun = InsetCommand::params2string(params_);
828 dispatch(FuncRequest(getLfun(), lfun));
832 BiblioInfo const & GuiCitation::bibInfo() const
834 Buffer const & buf = documentBuffer();
835 buf.reloadBibInfoCache();
836 return buf.masterBibInfo();
840 void GuiCitation::saveSession() const
842 Dialog::saveSession();
845 sessionKey() + "/regex", regexp_->isChecked());
847 sessionKey() + "/casesensitive", casesense_->isChecked());
849 sessionKey() + "/autofind", instant_->isChecked());
851 sessionKey() + "/citestyle", style_);
855 void GuiCitation::restoreSession()
857 Dialog::restoreSession();
859 regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
860 casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
861 instant_->setChecked(settings.value(sessionKey() + "/autofind").toBool());
862 style_ = settings.value(sessionKey() + "/citestyle").toInt();
867 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
870 } // namespace frontend
873 #include "moc_GuiCitation.cpp"