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);
274 docstring const trans =
275 translateIfPossible(from_utf8(val));
276 starredCB->setText(toqstr(trans));
277 starredCB->setEnabled(haveSelection);
279 if (!currentStyle.startooltip.empty()) {
280 val = bp.documentClass().getCiteMacro(bp.citeEngineType(),
281 currentStyle.startooltip);
283 docstring const trans =
284 translateIfPossible(from_utf8(val));
285 starredCB->setToolTip(toqstr(trans));
289 // This is the default meaning of the starred commands
290 starredCB->setText(qt_("All aut&hors"));
291 starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\")"));
296 // Update the styles for the style combo, citationStyleCO, and mark the
297 // settings as changed. Called upon changing the cited keys (including
298 // merely reordering the keys) or editing the text before/after fields.
299 void GuiCitation::updateStyles()
301 BiblioInfo const & bi = bibInfo();
307 // Update the styles for the style combo, citationStyleCO.
308 void GuiCitation::updateStyles(BiblioInfo const & bi)
310 QStringList selected_keys = selected_model_.stringList();
311 int curr = selectedLV->model()->rowCount() - 1;
313 if (curr < 0 || selected_keys.empty()) {
314 citationStyleCO->clear();
315 citationStyleCO->setEnabled(false);
316 citationStyleLA->setEnabled(false);
320 static const size_t max_length = 80;
321 QStringList sty = citationStyles(bi, max_length);
325 citationStyleCO->setEnabled(false);
326 citationStyleLA->setEnabled(false);
327 citationStyleCO->clear();
331 citationStyleCO->blockSignals(true);
334 int const curindex = citationStyleCO->currentIndex();
335 int const oldIndex = (curindex < 0) ? style_ : curindex;
336 citationStyleCO->clear();
337 citationStyleCO->insertItems(0, sty);
338 citationStyleCO->setEnabled(true);
339 citationStyleLA->setEnabled(true);
341 if (oldIndex != -1 && oldIndex < citationStyleCO->count())
342 citationStyleCO->setCurrentIndex(oldIndex);
344 citationStyleCO->blockSignals(false);
348 void GuiCitation::fillFields(BiblioInfo const & bi)
350 fieldsCO->blockSignals(true);
351 int const oldIndex = fieldsCO->currentIndex();
353 QStringList const fields = to_qstring_list(bi.getFields());
354 fieldsCO->insertItem(0, qt_("All fields"));
355 fieldsCO->insertItem(1, qt_("Keys"));
356 fieldsCO->insertItems(2, fields);
357 if (oldIndex != -1 && oldIndex < fieldsCO->count())
358 fieldsCO->setCurrentIndex(oldIndex);
359 fieldsCO->blockSignals(false);
363 void GuiCitation::fillEntries(BiblioInfo const & bi)
365 entriesCO->blockSignals(true);
366 int const oldIndex = entriesCO->currentIndex();
368 QStringList const entries = to_qstring_list(bi.getEntries());
369 entriesCO->insertItem(0, qt_("All entry types"));
370 entriesCO->insertItems(1, entries);
371 if (oldIndex != -1 && oldIndex < entriesCO->count())
372 entriesCO->setCurrentIndex(oldIndex);
373 entriesCO->blockSignals(false);
377 bool GuiCitation::isSelected(QModelIndex const & idx)
379 QString const str = idx.data().toString();
380 return selected_model_.stringList().contains(str);
384 void GuiCitation::setButtons()
386 int const srows = selectedLV->model()->rowCount();
387 applyPB->setEnabled(srows > 0);
388 okPB->setEnabled(srows > 0);
392 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
394 if (!idx.isValid() || bi.empty()) {
395 infoML->document()->clear();
396 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
400 infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
401 QString const keytxt = toqstr(
402 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), true));
403 infoML->document()->setHtml(keytxt);
407 void GuiCitation::findText(QString const & text, bool reset)
409 //"All Fields" and "Keys" are the first two
410 int index = fieldsCO->currentIndex() - 2;
411 BiblioInfo const & bi = bibInfo();
412 vector<docstring> const & fields = bi.getFields();
415 if (index <= -1 || index >= int(fields.size()))
416 //either "All Fields" or "Keys" or an invalid value
417 field = from_ascii("");
419 field = fields[index];
422 bool const onlyKeys = index == -1;
424 //"All Entry Types" is first.
425 index = entriesCO->currentIndex() - 1;
426 vector<docstring> const & entries = bi.getEntries();
427 docstring entry_type;
428 if (index < 0 || index >= int(entries.size()))
429 entry_type = from_ascii("");
431 entry_type = entries[index];
433 bool const case_sentitive = casesense_->isChecked();
434 bool const reg_exp = regexp_->isChecked();
436 findKey(bi, text, onlyKeys, field, entry_type,
437 case_sentitive, reg_exp, reset);
439 //It'd be nice to save and restore the current selection in
440 //availableLV. Currently, we get an automatic reset, since the
447 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
449 findText(filter_->text(), true);
453 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
455 findText(filter_->text(), true);
459 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
461 if (index >= 0 && index < citationStyleCO->count()) {
462 vector<CitationStyle> const & styles = citeStyles_;
463 updateFormatting(styles[index]);
469 void GuiCitation::filterChanged(const QString & text)
471 if (!text.isEmpty()) {
472 if (instant_->isChecked())
473 findText(filter_->text());
476 findText(filter_->text());
481 void GuiCitation::filterPressed()
483 findText(filter_->text(), true);
487 void GuiCitation::resetFilter()
489 filter_->setText(QString());
490 findText(filter_->text(), true);
494 void GuiCitation::caseChanged()
496 findText(filter_->text());
500 void GuiCitation::regexChanged()
502 findText(filter_->text());
506 void GuiCitation::updateFilterHint()
508 QString const hint = instant_->isChecked() ?
509 qt_("Enter string to filter the list of available citations") :
510 qt_("Enter string to filter the list of available citations and press <Enter>");
511 filter_->setToolTip(hint);
515 void GuiCitation::instantChanged(bool checked)
518 findText(filter_->text(), true);
524 void GuiCitation::changed()
530 void GuiCitation::applyParams(int const choice, bool full, bool force,
531 QString before, QString after)
533 if (cited_keys_.isEmpty())
536 vector<CitationStyle> const & styles = citeStyles_;
538 CitationStyle cs = styles[choice];
545 cs.forceUpperCase &= force;
546 cs.hasStarredVersion &= full;
547 string const command = citationStyleToString(cs);
549 params_.setCmdName(command);
550 params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
551 params_["before"] = qstring_to_ucs4(before);
552 params_["after"] = qstring_to_ucs4(after);
557 void GuiCitation::clearSelection()
560 selected_model_.setStringList(cited_keys_);
564 void GuiCitation::init()
566 // Make the list of all available bibliography keys
567 BiblioInfo const & bi = bibInfo();
568 all_keys_ = to_qstring_list(bi.getKeys());
569 available_model_.setStringList(all_keys_);
571 // Ditto for the keys cited in this inset
572 QString str = toqstr(params_["key"]);
576 cited_keys_ = str.split(",");
577 selected_model_.setStringList(cited_keys_);
579 // Initialize the drop downs
583 // Initialize the citation formatting
584 string const & cmd = params_.getCmdName();
585 CitationStyle const cs =
586 citationStyleFromString(cmd, documentBuffer().params());
587 forceuppercaseCB->setChecked(cs.forceUpperCase);
588 starredCB->setChecked(cs.hasStarredVersion &&
589 documentBuffer().params().fullAuthorList());
590 textBeforeED->setText(toqstr(params_["before"]));
591 textAfterED->setText(toqstr(params_["after"]));
593 // Update the interface
596 if (selected_model_.rowCount()) {
597 selectedLV->blockSignals(true);
598 selectedLV->setFocus();
599 QModelIndex idx = selected_model_.index(0, 0);
600 selectedLV->selectionModel()->select(idx,
601 QItemSelectionModel::ClearAndSelect);
602 selectedLV->blockSignals(false);
604 // Find the citation style
605 vector<string> const & cmds = citeCmds_;
606 vector<string>::const_iterator cit =
607 std::find(cmds.begin(), cmds.end(), cs.name);
609 if (cit != cmds.end())
610 i = int(cit - cmds.begin());
612 // Set the style combo appropriately
613 citationStyleCO->blockSignals(true);
614 citationStyleCO->setCurrentIndex(i);
615 citationStyleCO->blockSignals(false);
616 updateFormatting(citeStyles_[i]);
618 availableLV->setFocus();
620 applyPB->setEnabled(false);
621 okPB->setEnabled(false);
625 void GuiCitation::findKey(BiblioInfo const & bi,
626 QString const & str, bool only_keys,
627 docstring field, docstring entry_type,
628 bool case_sensitive, bool reg_exp, bool reset)
631 // This should be moved to a class member.
632 // Used for optimisation: store last searched string.
633 static QString last_searched_string;
634 // Used to disable the above optimisation.
635 static bool last_case_sensitive;
636 static bool last_reg_exp;
637 // Reset last_searched_string in case of changed option.
638 if (last_case_sensitive != case_sensitive
639 || last_reg_exp != reg_exp) {
640 LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
641 last_searched_string.clear();
643 // save option for next search.
644 last_case_sensitive = case_sensitive;
645 last_reg_exp = reg_exp;
647 Qt::CaseSensitivity qtcase = case_sensitive ?
648 Qt::CaseSensitive: Qt::CaseInsensitive;
650 // If new string (str) contains the last searched one...
652 !last_searched_string.isEmpty() &&
654 str.contains(last_searched_string, qtcase))
655 // ... then only search within already found list.
656 keys = available_model_.stringList();
658 // ... else search all keys.
660 // save searched string for next search.
661 last_searched_string = str;
665 // First, filter by entry_type, which will be faster than
666 // what follows, so we may get to do that on less.
667 vector<docstring> keyVector = to_docstring_vector(keys);
668 filterByEntryType(bi, keyVector, entry_type);
671 result = to_qstring_list(keyVector);
673 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
674 qstring_to_ucs4(str), field, case_sensitive, reg_exp));
676 available_model_.setStringList(result);
680 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
682 docstring const before = qstring_to_ucs4(textBeforeED->text());
683 docstring const after = qstring_to_ucs4(textAfterED->text());
684 vector<docstring> const keys = to_docstring_vector(cited_keys_);
685 vector<CitationStyle> styles = citeStyles_;
686 // FIXME: pass a dictionary instead of individual before, after, dialog, etc.
687 vector<docstring> ret = bi.getCiteStrings(keys, styles, documentBuffer(),
688 before, after, from_utf8("dialog"), max_size);
689 return to_qstring_list(ret);
693 void GuiCitation::setCitedKeys()
695 cited_keys_ = selected_model_.stringList();
700 bool GuiCitation::initialiseParams(string const & data)
702 InsetCommand::string2params(data, params_);
703 citeCmds_ = documentBuffer().params().citeCommands();
704 citeStyles_ = documentBuffer().params().citeStyles();
710 void GuiCitation::clearParams()
716 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
717 vector<docstring> & keyVector, docstring entry_type)
719 if (entry_type.empty())
722 vector<docstring>::iterator it = keyVector.begin();
723 vector<docstring>::iterator end = keyVector.end();
725 vector<docstring> result;
726 for (; it != end; ++it) {
727 docstring const key = *it;
728 BiblioInfo::const_iterator cit = bi.find(key);
731 if (cit->second.entryType() == entry_type)
732 result.push_back(key);
738 // Escape special chars.
739 // All characters are literals except: '.|*?+(){}[]^$\'
740 // These characters are literals when preceded by a "\", which is done here
741 // @todo: This function should be moved to support, and then the test in tests
742 // should be moved there as well.
743 static docstring escape_special_chars(docstring const & expr)
745 // Search for all chars '.|*?+(){}[^$]\'
746 // Note that '[', ']', and '\' must be escaped.
747 static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
749 // $& is an ECMAScript format expression that expands to all
750 // of the current match
751 #ifdef LYX_USE_STD_REGEX
752 // To prefix a matched expression with a single literal backslash, we
753 // need to escape it for the C++ compiler and use:
755 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
757 // A backslash in the format string starts an escape sequence in boost.
758 // Thus, to prefix a matched expression with a single literal backslash,
759 // we need to give two backslashes to the regex engine, and escape both
760 // for the C++ compiler and use:
762 return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
767 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
768 vector<docstring> const & keys_to_search, bool only_keys,
769 docstring const & search_expression, docstring field,
770 bool case_sensitive, bool regex)
772 vector<docstring> foundKeys;
774 docstring expr = trim(search_expression);
779 // We must escape special chars in the search_expr so that
780 // it is treated as a simple string by lyx::regex.
781 expr = escape_special_chars(expr);
785 reg_exp.assign(to_utf8(expr), case_sensitive ?
786 lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
787 } catch (lyx::regex_error const & e) {
788 // lyx::regex throws an exception if the regular expression is not
790 LYXERR(Debug::GUI, e.what());
791 return vector<docstring>();
794 vector<docstring>::const_iterator it = keys_to_search.begin();
795 vector<docstring>::const_iterator end = keys_to_search.end();
796 for (; it != end; ++it ) {
797 BiblioInfo::const_iterator info = bi.find(*it);
798 if (info == bi.end())
801 BibTeXInfo const & kvm = info->second;
805 else if (field.empty())
806 data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
808 data = to_utf8(kvm[field]);
814 if (lyx::regex_search(data, reg_exp))
815 foundKeys.push_back(*it);
817 catch (lyx::regex_error const & e) {
818 LYXERR(Debug::GUI, e.what());
819 return vector<docstring>();
826 void GuiCitation::dispatchParams()
828 std::string const lfun = InsetCommand::params2string(params_);
829 dispatch(FuncRequest(getLfun(), lfun));
833 BiblioInfo const & GuiCitation::bibInfo() const
835 Buffer const & buf = documentBuffer();
836 buf.reloadBibInfoCache();
837 return buf.masterBibInfo();
841 void GuiCitation::saveSession() const
843 Dialog::saveSession();
846 sessionKey() + "/regex", regexp_->isChecked());
848 sessionKey() + "/casesensitive", casesense_->isChecked());
850 sessionKey() + "/autofind", instant_->isChecked());
852 sessionKey() + "/citestyle", style_);
856 void GuiCitation::restoreSession()
858 Dialog::restoreSession();
860 regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
861 casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
862 instant_->setChecked(settings.value(sessionKey() + "/autofind").toBool());
863 style_ = settings.value(sessionKey() + "/citestyle").toInt();
868 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
871 } // namespace frontend
874 #include "moc_GuiCitation.cpp"