]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCitation.cpp
Speed up exit time
[lyx.git] / src / frontends / qt4 / GuiCitation.cpp
1
2 /**
3  * \file GuiCitation.cpp
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Angus Leeming
8  * \author Kalle Dalheimer
9  * \author Abdelrazak Younes
10  * \author Richard Heck
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "GuiCitation.h"
18
19 #include "GuiApplication.h"
20 #include "GuiSelectionManager.h"
21 #include "LyXToolBox.h"
22 #include "qt_helpers.h"
23
24 #include "Buffer.h"
25 #include "BufferView.h"
26 #include "BiblioInfo.h"
27 #include "BufferParams.h"
28 #include "FuncRequest.h"
29
30 #include "insets/InsetCommand.h"
31
32 #include "support/debug.h"
33 #include "support/docstring.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
36
37 #include <QCloseEvent>
38 #include <QMenu>
39 #include <QSettings>
40 #include <QShowEvent>
41 #include <QVariant>
42
43 #include <vector>
44 #include <string>
45
46 #undef KeyPress
47
48 #include "support/regex.h"
49
50 #include <algorithm>
51 #include <string>
52 #include <vector>
53
54 using namespace std;
55 using namespace lyx::support;
56
57 namespace lyx {
58 namespace frontend {
59
60 // FIXME THREAD
61 // I am guessing that it would not hurt to make these private members.
62 static vector<string> citeCmds_;
63 static vector<CitationStyle> citeStyles_;
64
65
66 template<typename String>
67 static QStringList to_qstring_list(vector<String> const & v)
68 {
69         QStringList qlist;
70
71         for (size_t i = 0; i != v.size(); ++i) {
72                 if (v[i].empty())
73                         continue;
74                 qlist.append(lyx::toqstr(v[i]));
75         }
76         return qlist;
77 }
78
79
80 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
81 {
82         vector<lyx::docstring> v;
83         for (int i = 0; i != qlist.size(); ++i) {
84                 if (qlist[i].isEmpty())
85                         continue;
86                 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
87         }
88         return v;
89 }
90
91
92 GuiCitation::GuiCitation(GuiView & lv)
93         : DialogView(lv, "citation", qt_("Citation")),
94           params_(insetCode("citation"))
95 {
96         setupUi(this);
97
98         // The filter bar
99         filter_ = new FancyLineEdit(this);
100 #if QT_VERSION >= 0x040600
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 #endif
106 #if QT_VERSION >= 0x040700
107         filter_->setPlaceholderText(qt_("All avail. citations"));
108 #endif
109
110         filterBarL->addWidget(filter_, 0);
111         findKeysLA->setBuddy(filter_);
112
113         // Add search options as button menu
114         regexp_ = new QAction(qt_("Regular e&xpression"), this);
115         regexp_->setCheckable(true);
116         casesense_ = new QAction(qt_("Case se&nsitive"), this);
117         casesense_->setCheckable(true);
118         instant_ = new QAction(qt_("Search as you &type"), this);
119         instant_->setCheckable(true);
120         instant_->setChecked(true);
121
122         QMenu * searchOpts = new QMenu(this);
123         searchOpts->addAction(regexp_);
124         searchOpts->addAction(casesense_);
125         searchOpts->addAction(instant_);
126         searchOptionsPB->setMenu(searchOpts);
127
128         connect(citationStyleCO, SIGNAL(activated(int)),
129                 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
130         connect(fulllistCB, SIGNAL(clicked()),
131                 this, SLOT(changed()));
132         connect(forceuppercaseCB, SIGNAL(clicked()),
133                 this, SLOT(changed()));
134         connect(textBeforeED, SIGNAL(textChanged(QString)),
135                 this, SLOT(updateStyles()));
136         connect(textAfterED, SIGNAL(textChanged(QString)),
137                 this, SLOT(updateStyles()));
138         connect(textBeforeED, SIGNAL(returnPressed()),
139                 this, SLOT(on_okPB_clicked()));
140         connect(textAfterED, SIGNAL(returnPressed()),
141                 this, SLOT(on_okPB_clicked()));
142
143         selectionManager = new GuiSelectionManager(availableLV, selectedLV,
144                         addPB, deletePB, upPB, downPB, &available_model_, &selected_model_);
145         connect(selectionManager, SIGNAL(selectionChanged()),
146                 this, SLOT(setCitedKeys()));
147         connect(selectionManager, SIGNAL(updateHook()),
148                 this, SLOT(updateControls()));
149         connect(selectionManager, SIGNAL(okHook()),
150                 this, SLOT(on_okPB_clicked()));
151
152         connect(filter_, SIGNAL(rightButtonClicked()),
153                 this, SLOT(resetFilter()));
154         connect(filter_, SIGNAL(textEdited(QString)),
155                 this, SLOT(filterChanged(QString)));
156         connect(filter_, SIGNAL(returnPressed()),
157                 this, SLOT(filterPressed()));
158         connect(regexp_, SIGNAL(triggered()),
159                 this, SLOT(regexChanged()));
160         connect(casesense_, SIGNAL(triggered()),
161                 this, SLOT(caseChanged()));
162         connect(instant_, SIGNAL(triggered(bool)),
163                 this, SLOT(instantChanged(bool)));
164
165         setFocusProxy(filter_);
166 }
167
168
169 GuiCitation::~GuiCitation()
170 {
171         delete selectionManager;
172 }
173
174
175 void GuiCitation::closeEvent(QCloseEvent * e)
176 {
177         clearSelection();
178         DialogView::closeEvent(e);
179 }
180
181
182 void GuiCitation::applyView()
183 {
184         int const choice = max(0, citationStyleCO->currentIndex());
185         style_ = choice;
186         bool const full  = fulllistCB->isChecked();
187         bool const force = forceuppercaseCB->isChecked();
188
189         QString const before = textBeforeED->text();
190         QString const after = textAfterED->text();
191
192         applyParams(choice, full, force, before, after);
193 }
194
195
196 void GuiCitation::showEvent(QShowEvent * e)
197 {
198         filter_->clear();
199         availableLV->setFocus();
200         DialogView::showEvent(e);
201 }
202
203
204 void GuiCitation::on_okPB_clicked()
205 {
206         applyView();
207         clearSelection();
208         hide();
209 }
210
211
212 void GuiCitation::on_cancelPB_clicked()
213 {
214         clearSelection();
215         hide();
216 }
217
218
219 void GuiCitation::on_applyPB_clicked()
220 {
221         applyView();
222 }
223
224
225 void GuiCitation::on_restorePB_clicked()
226 {
227         init();
228         updateFilterHint();
229 }
230
231
232 void GuiCitation::updateControls()
233 {
234         BiblioInfo const & bi = bibInfo();
235         updateControls(bi);
236 }
237
238
239 // The main point of separating this out is that the fill*() methods
240 // called in update() do not need to be called for INTERNAL updates,
241 // such as when addPB is pressed, as the list of fields, entries, etc,
242 // will not have changed.
243 void GuiCitation::updateControls(BiblioInfo const & bi)
244 {
245         QModelIndex idx = selectionManager->getSelectedIndex();
246         updateInfo(bi, idx);
247         int i = citationStyleCO->currentIndex();
248         if (i == -1)
249                 i = 0;
250         updateFormatting(citeStyles_[i]);
251         selectionManager->update();
252 }
253
254
255 void GuiCitation::updateFormatting(CitationStyle currentStyle)
256 {
257         bool const force = currentStyle.forceUpperCase;
258         bool const full = currentStyle.fullAuthorList &&
259                 documentBuffer().params().fullAuthorList();
260         bool const textbefore = currentStyle.textBefore;
261         bool const textafter = currentStyle.textAfter;
262
263         bool const haveSelection =
264                 selectedLV->model()->rowCount() > 0;
265
266         forceuppercaseCB->setEnabled(force && haveSelection);
267         fulllistCB->setEnabled(full && haveSelection);
268         textBeforeED->setEnabled(textbefore && haveSelection);
269         textBeforeLA->setEnabled(textbefore && haveSelection);
270         textAfterED->setEnabled(textafter && haveSelection);
271         textAfterLA->setEnabled(textafter && haveSelection);
272         citationStyleCO->setEnabled(haveSelection);
273         citationStyleLA->setEnabled(haveSelection);
274 }
275
276
277 // Update the styles for the style combo, citationStyleCO, and mark the
278 // settings as changed. Called upon changing the cited keys (including
279 // merely reordering the keys) or editing the text before/after fields.
280 void GuiCitation::updateStyles()
281 {
282         BiblioInfo const & bi = bibInfo();
283         updateStyles(bi);
284         changed();
285 }
286
287
288 // Update the styles for the style combo, citationStyleCO.
289 void GuiCitation::updateStyles(BiblioInfo const & bi)
290 {
291         QStringList selected_keys = selected_model_.stringList();
292         int curr = selectedLV->model()->rowCount() - 1;
293
294         if (curr < 0 || selected_keys.empty()) {
295                 citationStyleCO->clear();
296                 citationStyleCO->setEnabled(false);
297                 citationStyleLA->setEnabled(false);
298                 return;
299         }
300
301         static const size_t max_length = 80;
302         QStringList sty = citationStyles(bi, max_length);
303
304         if (sty.isEmpty()) {
305                 // some error
306                 citationStyleCO->setEnabled(false);
307                 citationStyleLA->setEnabled(false);
308                 citationStyleCO->clear();
309                 return;
310         }
311
312         citationStyleCO->blockSignals(true);
313
314         // save old index
315         int const oldIndex = citationStyleCO->currentIndex();
316         citationStyleCO->clear();
317         citationStyleCO->insertItems(0, sty);
318         citationStyleCO->setEnabled(true);
319         citationStyleLA->setEnabled(true);
320         // restore old index
321         if (oldIndex != -1 && oldIndex < citationStyleCO->count())
322                 citationStyleCO->setCurrentIndex(oldIndex);
323
324         citationStyleCO->blockSignals(false);
325 }
326
327
328 void GuiCitation::fillFields(BiblioInfo const & bi)
329 {
330         fieldsCO->blockSignals(true);
331         int const oldIndex = fieldsCO->currentIndex();
332         fieldsCO->clear();
333         QStringList const fields = to_qstring_list(bi.getFields());
334         fieldsCO->insertItem(0, qt_("All fields"));
335         fieldsCO->insertItem(1, qt_("Keys"));
336         fieldsCO->insertItems(2, fields);
337         if (oldIndex != -1 && oldIndex < fieldsCO->count())
338                 fieldsCO->setCurrentIndex(oldIndex);
339         fieldsCO->blockSignals(false);
340 }
341
342
343 void GuiCitation::fillEntries(BiblioInfo const & bi)
344 {
345         entriesCO->blockSignals(true);
346         int const oldIndex = entriesCO->currentIndex();
347         entriesCO->clear();
348         QStringList const entries = to_qstring_list(bi.getEntries());
349         entriesCO->insertItem(0, qt_("All entry types"));
350         entriesCO->insertItems(1, entries);
351         if (oldIndex != -1 && oldIndex < entriesCO->count())
352                 entriesCO->setCurrentIndex(oldIndex);
353         entriesCO->blockSignals(false);
354 }
355
356
357 bool GuiCitation::isSelected(QModelIndex const & idx)
358 {
359         QString const str = idx.data().toString();
360         return selected_model_.stringList().contains(str);
361 }
362
363
364 void GuiCitation::setButtons()
365 {
366         int const srows = selectedLV->model()->rowCount();
367         applyPB->setEnabled(srows > 0);
368         okPB->setEnabled(srows > 0);
369 }
370
371
372 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
373 {
374         if (!idx.isValid() || bi.empty()) {
375                 infoML->document()->clear();
376                 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
377                 return;
378         }
379
380         infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
381         QString const keytxt = toqstr(
382                 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), true));
383         infoML->document()->setHtml(keytxt);
384 }
385
386
387 void GuiCitation::findText(QString const & text, bool reset)
388 {
389         //"All Fields" and "Keys" are the first two
390         int index = fieldsCO->currentIndex() - 2;
391         BiblioInfo const & bi = bibInfo();
392         vector<docstring> const & fields = bi.getFields();
393         docstring field;
394
395         if (index <= -1 || index >= int(fields.size()))
396                 //either "All Fields" or "Keys" or an invalid value
397                 field = from_ascii("");
398         else
399                 field = fields[index];
400
401         //Was it "Keys"?
402         bool const onlyKeys = index == -1;
403
404         //"All Entry Types" is first.
405         index = entriesCO->currentIndex() - 1;
406         vector<docstring> const & entries = bi.getEntries();
407         docstring entry_type;
408         if (index < 0 || index >= int(entries.size()))
409                 entry_type = from_ascii("");
410         else
411                 entry_type = entries[index];
412
413         bool const case_sentitive = casesense_->isChecked();
414         bool const reg_exp = regexp_->isChecked();
415
416         findKey(bi, text, onlyKeys, field, entry_type,
417                        case_sentitive, reg_exp, reset);
418         //FIXME
419         //It'd be nice to save and restore the current selection in
420         //availableLV. Currently, we get an automatic reset, since the
421         //model is reset.
422
423         updateControls(bi);
424 }
425
426
427 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
428 {
429         findText(filter_->text(), true);
430 }
431
432
433 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
434 {
435         findText(filter_->text(), true);
436 }
437
438
439 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
440 {
441         if (index >= 0 && index < citationStyleCO->count()) {
442                 vector<CitationStyle> const & styles = citeStyles_;
443                 updateFormatting(styles[index]);
444                 changed();
445         }
446 }
447
448
449 void GuiCitation::filterChanged(const QString & text)
450 {
451         if (!text.isEmpty()) {
452                 if (instant_->isChecked())
453                         findText(filter_->text());
454                 return;
455         }
456         findText(filter_->text());
457         filter_->setFocus();
458 }
459
460
461 void GuiCitation::filterPressed()
462 {
463         findText(filter_->text(), true);
464 }
465
466
467 void GuiCitation::resetFilter()
468 {
469         filter_->setText(QString());
470         findText(filter_->text(), true);
471 }
472
473
474 void GuiCitation::caseChanged()
475 {
476         findText(filter_->text());
477 }
478
479
480 void GuiCitation::regexChanged()
481 {
482         findText(filter_->text());
483 }
484
485
486 void GuiCitation::updateFilterHint()
487 {
488         QString const hint = instant_->isChecked() ?
489                 qt_("Enter string to filter the list of available citations") :
490                 qt_("Enter string to filter the list of available citations and press <Enter>");
491         filter_->setToolTip(hint);
492 }
493
494
495 void GuiCitation::instantChanged(bool checked)
496 {
497         if (checked)
498                 findText(filter_->text(), true);
499
500         updateFilterHint();
501 }
502
503
504 void GuiCitation::changed()
505 {
506         setButtons();
507 }
508
509
510 void GuiCitation::applyParams(int const choice, bool full, bool force,
511         QString before, QString after)
512 {
513         if (cited_keys_.isEmpty())
514                 return;
515
516         vector<CitationStyle> const & styles = citeStyles_;
517
518         CitationStyle cs = styles[choice];
519
520         if (!cs.textBefore)
521                 before.clear();
522         if (!cs.textAfter)
523                 after.clear();
524
525         cs.forceUpperCase &= force;
526         cs.fullAuthorList &= full;
527         string const command = citationStyleToString(cs);
528
529         params_.setCmdName(command);
530         params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
531         params_["before"] = qstring_to_ucs4(before);
532         params_["after"] = qstring_to_ucs4(after);
533         dispatchParams();
534 }
535
536
537 void GuiCitation::clearSelection()
538 {
539         cited_keys_.clear();
540         selected_model_.setStringList(cited_keys_);
541 }
542
543
544 void GuiCitation::init()
545 {
546         // Make the list of all available bibliography keys
547         BiblioInfo const & bi = bibInfo();
548         all_keys_ = to_qstring_list(bi.getKeys());
549         available_model_.setStringList(all_keys_);
550
551         // Ditto for the keys cited in this inset
552         QString str = toqstr(params_["key"]);
553         if (str.isEmpty())
554                 cited_keys_.clear();
555         else
556                 cited_keys_ = str.split(",");
557         selected_model_.setStringList(cited_keys_);
558
559         // Initialize the drop downs
560         fillEntries(bi);
561         fillFields(bi);
562
563         // Initialize the citation formatting
564         string const & cmd = params_.getCmdName();
565         CitationStyle const cs = citationStyleFromString(cmd);
566         forceuppercaseCB->setChecked(cs.forceUpperCase);
567         fulllistCB->setChecked(cs.fullAuthorList &&
568                 documentBuffer().params().fullAuthorList());
569         textBeforeED->setText(toqstr(params_["before"]));
570         textAfterED->setText(toqstr(params_["after"]));
571
572         // Update the interface
573         updateControls(bi);
574         updateStyles(bi);
575         if (selected_model_.rowCount()) {
576                 selectedLV->blockSignals(true);
577                 selectedLV->setFocus();
578                 QModelIndex idx = selected_model_.index(0, 0);
579                 selectedLV->selectionModel()->select(idx,
580                                 QItemSelectionModel::ClearAndSelect);
581                 selectedLV->blockSignals(false);
582
583                 // Find the citation style
584                 vector<string> const & cmds = citeCmds_;
585                 vector<string>::const_iterator cit =
586                         std::find(cmds.begin(), cmds.end(), cs.cmd);
587                 int i = 0;
588                 if (cit != cmds.end())
589                         i = int(cit - cmds.begin());
590
591                 // Set the style combo appropriately
592                 citationStyleCO->blockSignals(true);
593                 citationStyleCO->setCurrentIndex(i);
594                 citationStyleCO->blockSignals(false);
595                 updateFormatting(citeStyles_[i]);
596         } else
597                 availableLV->setFocus();
598
599         applyPB->setEnabled(false);
600         okPB->setEnabled(false);
601 }
602
603
604 void GuiCitation::findKey(BiblioInfo const & bi,
605         QString const & str, bool only_keys,
606         docstring field, docstring entry_type,
607         bool case_sensitive, bool reg_exp, bool reset)
608 {
609         // FIXME THREAD
610         // Used for optimisation: store last searched string.
611         static QString last_searched_string;
612         // Used to disable the above optimisation.
613         static bool last_case_sensitive;
614         static bool last_reg_exp;
615         // Reset last_searched_string in case of changed option.
616         if (last_case_sensitive != case_sensitive
617                 || last_reg_exp != reg_exp) {
618                         LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
619                 last_searched_string.clear();
620         }
621         // save option for next search.
622         last_case_sensitive = case_sensitive;
623         last_reg_exp = reg_exp;
624
625         Qt::CaseSensitivity qtcase = case_sensitive ?
626                         Qt::CaseSensitive: Qt::CaseInsensitive;
627         QStringList keys;
628         // If new string (str) contains the last searched one...
629         if (!reset &&
630                 !last_searched_string.isEmpty() &&
631                 str.size() > 1 &&
632                 str.contains(last_searched_string, qtcase))
633                 // ... then only search within already found list.
634                 keys = available_model_.stringList();
635         else
636                 // ... else search all keys.
637                 keys = all_keys_;
638         // save searched string for next search.
639         last_searched_string = str;
640
641         QStringList result;
642
643         // First, filter by entry_type, which will be faster than
644         // what follows, so we may get to do that on less.
645         vector<docstring> keyVector = to_docstring_vector(keys);
646         filterByEntryType(bi, keyVector, entry_type);
647
648         if (str.isEmpty())
649                 result = to_qstring_list(keyVector);
650         else
651                 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
652                         qstring_to_ucs4(str), field, case_sensitive, reg_exp));
653
654         available_model_.setStringList(result);
655 }
656
657
658 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
659 {
660         docstring const before = qstring_to_ucs4(textBeforeED->text());
661         docstring const after = qstring_to_ucs4(textAfterED->text());
662         vector<docstring> const keys = to_docstring_vector(cited_keys_);
663         vector<CitationStyle> styles = citeStyles_;
664         // FIXME: pass a dictionary instead of individual before, after, dialog, etc.
665         vector<docstring> ret = bi.getCiteStrings(keys, styles, documentBuffer(),
666                 before, after, from_utf8("dialog"), max_size);
667         return to_qstring_list(ret);
668 }
669
670
671 void GuiCitation::setCitedKeys()
672 {
673         cited_keys_ = selected_model_.stringList();
674         updateStyles();
675 }
676
677
678 bool GuiCitation::initialiseParams(string const & data)
679 {
680         InsetCommand::string2params(data, params_);
681         citeCmds_ = documentBuffer().params().citeCommands();
682         citeStyles_ = documentBuffer().params().citeStyles();
683         init();
684         return true;
685 }
686
687
688 void GuiCitation::clearParams()
689 {
690         params_.clear();
691 }
692
693
694 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
695         vector<docstring> & keyVector, docstring entry_type)
696 {
697         if (entry_type.empty())
698                 return;
699
700         vector<docstring>::iterator it = keyVector.begin();
701         vector<docstring>::iterator end = keyVector.end();
702
703         vector<docstring> result;
704         for (; it != end; ++it) {
705                 docstring const key = *it;
706                 BiblioInfo::const_iterator cit = bi.find(key);
707                 if (cit == bi.end())
708                         continue;
709                 if (cit->second.entryType() == entry_type)
710                         result.push_back(key);
711         }
712         keyVector = result;
713 }
714
715
716 // Escape special chars.
717 // All characters are literals except: '.|*?+(){}[]^$\'
718 // These characters are literals when preceded by a "\", which is done here
719 // @todo: This function should be moved to support, and then the test in tests
720 //        should be moved there as well.
721 static docstring escape_special_chars(docstring const & expr)
722 {
723         // Search for all chars '.|*?+(){}[^$]\'
724         // Note that '[', ']', and '\' must be escaped.
725         static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
726
727         // $& is an ECMAScript format expression that expands to all
728         // of the current match
729 #if defined(LYX_USE_CXX11) && defined(LYX_USE_STD_REGEX)
730         // To prefix a matched expression with a single literal backslash, we
731         // need to escape it for the C++ compiler and use:
732         // FIXME: UNICODE
733         return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
734 #else
735         // A backslash in the format string starts an escape sequence in boost.
736         // Thus, to prefix a matched expression with a single literal backslash,
737         // we need to give two backslashes to the regex engine, and escape both
738         // for the C++ compiler and use:
739         // FIXME: UNICODE
740         return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
741 #endif
742 }
743
744
745 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
746         vector<docstring> const & keys_to_search, bool only_keys,
747         docstring const & search_expression, docstring field,
748         bool case_sensitive, bool regex)
749 {
750         vector<docstring> foundKeys;
751
752         docstring expr = trim(search_expression);
753         if (expr.empty())
754                 return foundKeys;
755
756         if (!regex)
757                 // We must escape special chars in the search_expr so that
758                 // it is treated as a simple string by lyx::regex.
759                 expr = escape_special_chars(expr);
760
761         lyx::regex reg_exp;
762         try {
763                 reg_exp.assign(to_utf8(expr), case_sensitive ?
764                         lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
765         } catch (lyx::regex_error const & e) {
766                 // lyx::regex throws an exception if the regular expression is not
767                 // valid.
768                 LYXERR(Debug::GUI, e.what());
769                 return vector<docstring>();
770         }
771
772         vector<docstring>::const_iterator it = keys_to_search.begin();
773         vector<docstring>::const_iterator end = keys_to_search.end();
774         for (; it != end; ++it ) {
775                 BiblioInfo::const_iterator info = bi.find(*it);
776                 if (info == bi.end())
777                         continue;
778
779                 BibTeXInfo const & kvm = info->second;
780                 string data;
781                 if (only_keys)
782                         data = to_utf8(*it);
783                 else if (field.empty())
784                         data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
785                 else
786                         data = to_utf8(kvm[field]);
787
788                 if (data.empty())
789                         continue;
790
791                 try {
792                         if (lyx::regex_search(data, reg_exp))
793                                 foundKeys.push_back(*it);
794                 }
795                 catch (lyx::regex_error const & e) {
796                         LYXERR(Debug::GUI, e.what());
797                         return vector<docstring>();
798                 }
799         }
800         return foundKeys;
801 }
802
803
804 void GuiCitation::dispatchParams()
805 {
806         std::string const lfun = InsetCommand::params2string(params_);
807         dispatch(FuncRequest(getLfun(), lfun));
808 }
809
810
811 BiblioInfo const & GuiCitation::bibInfo() const
812 {
813         Buffer const & buf = documentBuffer();
814         buf.reloadBibInfoCache();
815         return buf.masterBibInfo();
816 }
817
818
819 void GuiCitation::saveSession(QSettings & settings) const
820 {
821         Dialog::saveSession(settings);
822         settings.setValue(
823                 sessionKey() + "/regex", regexp_->isChecked());
824         settings.setValue(
825                 sessionKey() + "/casesensitive", casesense_->isChecked());
826         settings.setValue(
827                 sessionKey() + "/autofind", instant_->isChecked());
828 }
829
830
831 void GuiCitation::restoreSession()
832 {
833         Dialog::restoreSession();
834         QSettings settings;
835         regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
836         casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
837         instant_->setChecked(settings.value(sessionKey() + "/autofind").toBool());
838         updateFilterHint();
839 }
840
841
842 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
843
844
845 } // namespace frontend
846 } // namespace lyx
847
848 #include "moc_GuiCitation.cpp"
849