]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCitation.cpp
Merge branch 'master' into biblatex2
[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 "TextClass.h"
29 #include "FuncRequest.h"
30
31 #include "insets/InsetCommand.h"
32
33 #include "support/debug.h"
34 #include "support/docstring.h"
35 #include "support/gettext.h"
36 #include "support/lstrings.h"
37
38 #include <QCloseEvent>
39 #include <QMenu>
40 #include <QSettings>
41 #include <QShowEvent>
42 #include <QVariant>
43
44 #include <vector>
45 #include <string>
46
47 #undef KeyPress
48
49 #include "support/regex.h"
50
51 #include <algorithm>
52 #include <string>
53 #include <vector>
54
55 using namespace std;
56 using namespace lyx::support;
57
58 namespace lyx {
59 namespace frontend {
60
61 // FIXME THREAD
62 // I am guessing that it would not hurt to make these private members.
63 static vector<string> citeCmds_;
64 static vector<CitationStyle> citeStyles_;
65
66
67 template<typename String>
68 static QStringList to_qstring_list(vector<String> const & v)
69 {
70         QStringList qlist;
71
72         for (size_t i = 0; i != v.size(); ++i) {
73                 if (v[i].empty())
74                         continue;
75                 qlist.append(lyx::toqstr(v[i]));
76         }
77         return qlist;
78 }
79
80
81 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
82 {
83         vector<lyx::docstring> v;
84         for (int i = 0; i != qlist.size(); ++i) {
85                 if (qlist[i].isEmpty())
86                         continue;
87                 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
88         }
89         return v;
90 }
91
92
93 GuiCitation::GuiCitation(GuiView & lv)
94         : DialogView(lv, "citation", qt_("Citation")),
95           style_(0), params_(insetCode("citation"))
96 {
97         setupUi(this);
98
99         // The filter bar
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"));
106
107         filterBarL->addWidget(filter_, 0);
108         findKeysLA->setBuddy(filter_);
109
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);
118
119         QMenu * searchOpts = new QMenu(this);
120         searchOpts->addAction(regexp_);
121         searchOpts->addAction(casesense_);
122         searchOpts->addAction(instant_);
123         searchOptionsPB->setMenu(searchOpts);
124
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()));
139
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()));
148
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)));
161
162         setFocusProxy(filter_);
163 }
164
165
166 GuiCitation::~GuiCitation()
167 {
168         delete selectionManager;
169 }
170
171
172 void GuiCitation::closeEvent(QCloseEvent * e)
173 {
174         clearSelection();
175         DialogView::closeEvent(e);
176 }
177
178
179 void GuiCitation::applyView()
180 {
181         int const choice = max(0, citationStyleCO->currentIndex());
182         style_ = choice;
183         bool const full  = starredCB->isChecked();
184         bool const force = forceuppercaseCB->isChecked();
185
186         QString const before = textBeforeED->text();
187         QString const after = textAfterED->text();
188
189         applyParams(choice, full, force, before, after);
190 }
191
192
193 void GuiCitation::showEvent(QShowEvent * e)
194 {
195         filter_->clear();
196         availableLV->setFocus();
197         DialogView::showEvent(e);
198 }
199
200
201 void GuiCitation::on_okPB_clicked()
202 {
203         applyView();
204         clearSelection();
205         hide();
206 }
207
208
209 void GuiCitation::on_cancelPB_clicked()
210 {
211         clearSelection();
212         hide();
213 }
214
215
216 void GuiCitation::on_applyPB_clicked()
217 {
218         applyView();
219 }
220
221
222 void GuiCitation::on_restorePB_clicked()
223 {
224         init();
225         updateFilterHint();
226 }
227
228
229 void GuiCitation::updateControls()
230 {
231         BiblioInfo const & bi = bibInfo();
232         updateControls(bi);
233 }
234
235
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)
241 {
242         QModelIndex idx = selectionManager->getSelectedIndex();
243         updateInfo(bi, idx);
244         selectionManager->update();
245 }
246
247
248 void GuiCitation::updateFormatting(CitationStyle currentStyle)
249 {
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;
256
257         bool const haveSelection =
258                 selectedLV->model()->rowCount() > 0;
259
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);
268
269         // Check if we have a custom string/tooltip for the starred version
270         if (starred && !currentStyle.stardesc.empty()) {
271                 string val =
272                         bp.documentClass().getCiteMacro(bp.citeEngineType(), currentStyle.stardesc);
273                 docstring guistring;
274                 if (!val.empty()) {
275                         guistring = translateIfPossible(from_utf8(val));
276                         starredCB->setText(toqstr(guistring));
277                         starredCB->setEnabled(haveSelection);
278                 }
279                 if (!currentStyle.startooltip.empty()) {
280                         val = bp.documentClass().getCiteMacro(bp.citeEngineType(),
281                                                               currentStyle.startooltip);
282                         if (!val.empty())
283                                 guistring = translateIfPossible(from_utf8(val));
284                 }
285                 // Tooltip might also be empty
286                 starredCB->setToolTip(toqstr(guistring));
287         } else {
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.\")"));
291         }
292 }
293
294
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()
299 {
300         BiblioInfo const & bi = bibInfo();
301         updateStyles(bi);
302         changed();
303 }
304
305
306 // Update the styles for the style combo, citationStyleCO.
307 void GuiCitation::updateStyles(BiblioInfo const & bi)
308 {
309         QStringList selected_keys = selected_model_.stringList();
310         int curr = selectedLV->model()->rowCount() - 1;
311
312         if (curr < 0 || selected_keys.empty()) {
313                 citationStyleCO->clear();
314                 citationStyleCO->setEnabled(false);
315                 citationStyleLA->setEnabled(false);
316                 return;
317         }
318
319         static const size_t max_length = 80;
320         QStringList sty = citationStyles(bi, max_length);
321
322         if (sty.isEmpty()) {
323                 // some error
324                 citationStyleCO->setEnabled(false);
325                 citationStyleLA->setEnabled(false);
326                 citationStyleCO->clear();
327                 return;
328         }
329
330         citationStyleCO->blockSignals(true);
331
332         // save old index
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);
339         // restore old index
340         if (oldIndex != -1 && oldIndex < citationStyleCO->count())
341                 citationStyleCO->setCurrentIndex(oldIndex);
342
343         citationStyleCO->blockSignals(false);
344 }
345
346
347 void GuiCitation::fillFields(BiblioInfo const & bi)
348 {
349         fieldsCO->blockSignals(true);
350         int const oldIndex = fieldsCO->currentIndex();
351         fieldsCO->clear();
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);
359 }
360
361
362 void GuiCitation::fillEntries(BiblioInfo const & bi)
363 {
364         entriesCO->blockSignals(true);
365         int const oldIndex = entriesCO->currentIndex();
366         entriesCO->clear();
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);
373 }
374
375
376 bool GuiCitation::isSelected(QModelIndex const & idx)
377 {
378         QString const str = idx.data().toString();
379         return selected_model_.stringList().contains(str);
380 }
381
382
383 void GuiCitation::setButtons()
384 {
385         int const srows = selectedLV->model()->rowCount();
386         applyPB->setEnabled(srows > 0);
387         okPB->setEnabled(srows > 0);
388 }
389
390
391 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
392 {
393         if (!idx.isValid() || bi.empty()) {
394                 infoML->document()->clear();
395                 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
396                 return;
397         }
398
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);
403 }
404
405
406 void GuiCitation::findText(QString const & text, bool reset)
407 {
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();
412         docstring field;
413
414         if (index <= -1 || index >= int(fields.size()))
415                 //either "All Fields" or "Keys" or an invalid value
416                 field = from_ascii("");
417         else
418                 field = fields[index];
419
420         //Was it "Keys"?
421         bool const onlyKeys = index == -1;
422
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("");
429         else
430                 entry_type = entries[index];
431
432         bool const case_sentitive = casesense_->isChecked();
433         bool const reg_exp = regexp_->isChecked();
434
435         findKey(bi, text, onlyKeys, field, entry_type,
436                        case_sentitive, reg_exp, reset);
437         //FIXME
438         //It'd be nice to save and restore the current selection in
439         //availableLV. Currently, we get an automatic reset, since the
440         //model is reset.
441
442         updateControls(bi);
443 }
444
445
446 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
447 {
448         findText(filter_->text(), true);
449 }
450
451
452 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
453 {
454         findText(filter_->text(), true);
455 }
456
457
458 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
459 {
460         if (index >= 0 && index < citationStyleCO->count()) {
461                 vector<CitationStyle> const & styles = citeStyles_;
462                 updateFormatting(styles[index]);
463                 changed();
464         }
465 }
466
467
468 void GuiCitation::filterChanged(const QString & text)
469 {
470         if (!text.isEmpty()) {
471                 if (instant_->isChecked())
472                         findText(filter_->text());
473                 return;
474         }
475         findText(filter_->text());
476         filter_->setFocus();
477 }
478
479
480 void GuiCitation::filterPressed()
481 {
482         findText(filter_->text(), true);
483 }
484
485
486 void GuiCitation::resetFilter()
487 {
488         filter_->setText(QString());
489         findText(filter_->text(), true);
490 }
491
492
493 void GuiCitation::caseChanged()
494 {
495         findText(filter_->text());
496 }
497
498
499 void GuiCitation::regexChanged()
500 {
501         findText(filter_->text());
502 }
503
504
505 void GuiCitation::updateFilterHint()
506 {
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);
511 }
512
513
514 void GuiCitation::instantChanged(bool checked)
515 {
516         if (checked)
517                 findText(filter_->text(), true);
518
519         updateFilterHint();
520 }
521
522
523 void GuiCitation::changed()
524 {
525         setButtons();
526 }
527
528
529 void GuiCitation::applyParams(int const choice, bool full, bool force,
530         QString before, QString after)
531 {
532         if (cited_keys_.isEmpty())
533                 return;
534
535         vector<CitationStyle> const & styles = citeStyles_;
536
537         CitationStyle cs = styles[choice];
538
539         if (!cs.textBefore)
540                 before.clear();
541         if (!cs.textAfter)
542                 after.clear();
543
544         cs.forceUpperCase &= force;
545         cs.hasStarredVersion &= full;
546         string const command = citationStyleToString(cs);
547
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);
552         dispatchParams();
553 }
554
555
556 void GuiCitation::clearSelection()
557 {
558         cited_keys_.clear();
559         selected_model_.setStringList(cited_keys_);
560 }
561
562
563 void GuiCitation::init()
564 {
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_);
569
570         // Ditto for the keys cited in this inset
571         QString str = toqstr(params_["key"]);
572         if (str.isEmpty())
573                 cited_keys_.clear();
574         else
575                 cited_keys_ = str.split(",");
576         selected_model_.setStringList(cited_keys_);
577
578         // Initialize the drop downs
579         fillEntries(bi);
580         fillFields(bi);
581
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"]));
591
592         // Update the interface
593         updateControls(bi);
594         updateStyles(bi);
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);
602
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);
607                 int i = 0;
608                 if (cit != cmds.end())
609                         i = int(cit - cmds.begin());
610
611                 // Set the style combo appropriately
612                 citationStyleCO->blockSignals(true);
613                 citationStyleCO->setCurrentIndex(i);
614                 citationStyleCO->blockSignals(false);
615                 updateFormatting(citeStyles_[i]);
616         } else
617                 availableLV->setFocus();
618
619         applyPB->setEnabled(false);
620         okPB->setEnabled(false);
621 }
622
623
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)
628 {
629         // FIXME THREAD
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();
641         }
642         // save option for next search.
643         last_case_sensitive = case_sensitive;
644         last_reg_exp = reg_exp;
645
646         Qt::CaseSensitivity qtcase = case_sensitive ?
647                         Qt::CaseSensitive: Qt::CaseInsensitive;
648         QStringList keys;
649         // If new string (str) contains the last searched one...
650         if (!reset &&
651                 !last_searched_string.isEmpty() &&
652                 str.size() > 1 &&
653                 str.contains(last_searched_string, qtcase))
654                 // ... then only search within already found list.
655                 keys = available_model_.stringList();
656         else
657                 // ... else search all keys.
658                 keys = all_keys_;
659         // save searched string for next search.
660         last_searched_string = str;
661
662         QStringList result;
663
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);
668
669         if (str.isEmpty())
670                 result = to_qstring_list(keyVector);
671         else
672                 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
673                         qstring_to_ucs4(str), field, case_sensitive, reg_exp));
674
675         available_model_.setStringList(result);
676 }
677
678
679 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
680 {
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);
689 }
690
691
692 void GuiCitation::setCitedKeys()
693 {
694         cited_keys_ = selected_model_.stringList();
695         updateStyles();
696 }
697
698
699 bool GuiCitation::initialiseParams(string const & data)
700 {
701         InsetCommand::string2params(data, params_);
702         citeCmds_ = documentBuffer().params().citeCommands();
703         citeStyles_ = documentBuffer().params().citeStyles();
704         init();
705         return true;
706 }
707
708
709 void GuiCitation::clearParams()
710 {
711         params_.clear();
712 }
713
714
715 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
716         vector<docstring> & keyVector, docstring entry_type)
717 {
718         if (entry_type.empty())
719                 return;
720
721         vector<docstring>::iterator it = keyVector.begin();
722         vector<docstring>::iterator end = keyVector.end();
723
724         vector<docstring> result;
725         for (; it != end; ++it) {
726                 docstring const key = *it;
727                 BiblioInfo::const_iterator cit = bi.find(key);
728                 if (cit == bi.end())
729                         continue;
730                 if (cit->second.entryType() == entry_type)
731                         result.push_back(key);
732         }
733         keyVector = result;
734 }
735
736
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)
743 {
744         // Search for all chars '.|*?+(){}[^$]\'
745         // Note that '[', ']', and '\' must be escaped.
746         static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
747
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:
753         // FIXME: UNICODE
754         return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
755 #else
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:
760         // FIXME: UNICODE
761         return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
762 #endif
763 }
764
765
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)
770 {
771         vector<docstring> foundKeys;
772
773         docstring expr = trim(search_expression);
774         if (expr.empty())
775                 return foundKeys;
776
777         if (!regex)
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);
781
782         lyx::regex reg_exp;
783         try {
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
788                 // valid.
789                 LYXERR(Debug::GUI, e.what());
790                 return vector<docstring>();
791         }
792
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())
798                         continue;
799
800                 BibTeXInfo const & kvm = info->second;
801                 string data;
802                 if (only_keys)
803                         data = to_utf8(*it);
804                 else if (field.empty())
805                         data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
806                 else
807                         data = to_utf8(kvm[field]);
808
809                 if (data.empty())
810                         continue;
811
812                 try {
813                         if (lyx::regex_search(data, reg_exp))
814                                 foundKeys.push_back(*it);
815                 }
816                 catch (lyx::regex_error const & e) {
817                         LYXERR(Debug::GUI, e.what());
818                         return vector<docstring>();
819                 }
820         }
821         return foundKeys;
822 }
823
824
825 void GuiCitation::dispatchParams()
826 {
827         std::string const lfun = InsetCommand::params2string(params_);
828         dispatch(FuncRequest(getLfun(), lfun));
829 }
830
831
832 BiblioInfo const & GuiCitation::bibInfo() const
833 {
834         Buffer const & buf = documentBuffer();
835         buf.reloadBibInfoCache();
836         return buf.masterBibInfo();
837 }
838
839
840 void GuiCitation::saveSession() const
841 {
842         Dialog::saveSession();
843         QSettings settings;
844         settings.setValue(
845                 sessionKey() + "/regex", regexp_->isChecked());
846         settings.setValue(
847                 sessionKey() + "/casesensitive", casesense_->isChecked());
848         settings.setValue(
849                 sessionKey() + "/autofind", instant_->isChecked());
850         settings.setValue(
851                 sessionKey() + "/citestyle", style_);
852 }
853
854
855 void GuiCitation::restoreSession()
856 {
857         Dialog::restoreSession();
858         QSettings settings;
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();
863         updateFilterHint();
864 }
865
866
867 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
868
869
870 } // namespace frontend
871 } // namespace lyx
872
873 #include "moc_GuiCitation.cpp"
874