]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCitation.cpp
Generalize starred cite commands
[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                 if (!val.empty()) {
274                         docstring const trans =
275                                 translateIfPossible(from_utf8(val));
276                         starredCB->setText(toqstr(trans));
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                                 docstring const trans =
284                                         translateIfPossible(from_utf8(val));
285                                 starredCB->setToolTip(toqstr(trans));
286                         }
287                 }
288         } else {
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.\")"));
292         }
293 }
294
295
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()
300 {
301         BiblioInfo const & bi = bibInfo();
302         updateStyles(bi);
303         changed();
304 }
305
306
307 // Update the styles for the style combo, citationStyleCO.
308 void GuiCitation::updateStyles(BiblioInfo const & bi)
309 {
310         QStringList selected_keys = selected_model_.stringList();
311         int curr = selectedLV->model()->rowCount() - 1;
312
313         if (curr < 0 || selected_keys.empty()) {
314                 citationStyleCO->clear();
315                 citationStyleCO->setEnabled(false);
316                 citationStyleLA->setEnabled(false);
317                 return;
318         }
319
320         static const size_t max_length = 80;
321         QStringList sty = citationStyles(bi, max_length);
322
323         if (sty.isEmpty()) {
324                 // some error
325                 citationStyleCO->setEnabled(false);
326                 citationStyleLA->setEnabled(false);
327                 citationStyleCO->clear();
328                 return;
329         }
330
331         citationStyleCO->blockSignals(true);
332
333         // save old index
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);
340         // restore old index
341         if (oldIndex != -1 && oldIndex < citationStyleCO->count())
342                 citationStyleCO->setCurrentIndex(oldIndex);
343
344         citationStyleCO->blockSignals(false);
345 }
346
347
348 void GuiCitation::fillFields(BiblioInfo const & bi)
349 {
350         fieldsCO->blockSignals(true);
351         int const oldIndex = fieldsCO->currentIndex();
352         fieldsCO->clear();
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);
360 }
361
362
363 void GuiCitation::fillEntries(BiblioInfo const & bi)
364 {
365         entriesCO->blockSignals(true);
366         int const oldIndex = entriesCO->currentIndex();
367         entriesCO->clear();
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);
374 }
375
376
377 bool GuiCitation::isSelected(QModelIndex const & idx)
378 {
379         QString const str = idx.data().toString();
380         return selected_model_.stringList().contains(str);
381 }
382
383
384 void GuiCitation::setButtons()
385 {
386         int const srows = selectedLV->model()->rowCount();
387         applyPB->setEnabled(srows > 0);
388         okPB->setEnabled(srows > 0);
389 }
390
391
392 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
393 {
394         if (!idx.isValid() || bi.empty()) {
395                 infoML->document()->clear();
396                 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
397                 return;
398         }
399
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);
404 }
405
406
407 void GuiCitation::findText(QString const & text, bool reset)
408 {
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();
413         docstring field;
414
415         if (index <= -1 || index >= int(fields.size()))
416                 //either "All Fields" or "Keys" or an invalid value
417                 field = from_ascii("");
418         else
419                 field = fields[index];
420
421         //Was it "Keys"?
422         bool const onlyKeys = index == -1;
423
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("");
430         else
431                 entry_type = entries[index];
432
433         bool const case_sentitive = casesense_->isChecked();
434         bool const reg_exp = regexp_->isChecked();
435
436         findKey(bi, text, onlyKeys, field, entry_type,
437                        case_sentitive, reg_exp, reset);
438         //FIXME
439         //It'd be nice to save and restore the current selection in
440         //availableLV. Currently, we get an automatic reset, since the
441         //model is reset.
442
443         updateControls(bi);
444 }
445
446
447 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
448 {
449         findText(filter_->text(), true);
450 }
451
452
453 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
454 {
455         findText(filter_->text(), true);
456 }
457
458
459 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
460 {
461         if (index >= 0 && index < citationStyleCO->count()) {
462                 vector<CitationStyle> const & styles = citeStyles_;
463                 updateFormatting(styles[index]);
464                 changed();
465         }
466 }
467
468
469 void GuiCitation::filterChanged(const QString & text)
470 {
471         if (!text.isEmpty()) {
472                 if (instant_->isChecked())
473                         findText(filter_->text());
474                 return;
475         }
476         findText(filter_->text());
477         filter_->setFocus();
478 }
479
480
481 void GuiCitation::filterPressed()
482 {
483         findText(filter_->text(), true);
484 }
485
486
487 void GuiCitation::resetFilter()
488 {
489         filter_->setText(QString());
490         findText(filter_->text(), true);
491 }
492
493
494 void GuiCitation::caseChanged()
495 {
496         findText(filter_->text());
497 }
498
499
500 void GuiCitation::regexChanged()
501 {
502         findText(filter_->text());
503 }
504
505
506 void GuiCitation::updateFilterHint()
507 {
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);
512 }
513
514
515 void GuiCitation::instantChanged(bool checked)
516 {
517         if (checked)
518                 findText(filter_->text(), true);
519
520         updateFilterHint();
521 }
522
523
524 void GuiCitation::changed()
525 {
526         setButtons();
527 }
528
529
530 void GuiCitation::applyParams(int const choice, bool full, bool force,
531         QString before, QString after)
532 {
533         if (cited_keys_.isEmpty())
534                 return;
535
536         vector<CitationStyle> const & styles = citeStyles_;
537
538         CitationStyle cs = styles[choice];
539
540         if (!cs.textBefore)
541                 before.clear();
542         if (!cs.textAfter)
543                 after.clear();
544
545         cs.forceUpperCase &= force;
546         cs.hasStarredVersion &= full;
547         string const command = citationStyleToString(cs);
548
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);
553         dispatchParams();
554 }
555
556
557 void GuiCitation::clearSelection()
558 {
559         cited_keys_.clear();
560         selected_model_.setStringList(cited_keys_);
561 }
562
563
564 void GuiCitation::init()
565 {
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_);
570
571         // Ditto for the keys cited in this inset
572         QString str = toqstr(params_["key"]);
573         if (str.isEmpty())
574                 cited_keys_.clear();
575         else
576                 cited_keys_ = str.split(",");
577         selected_model_.setStringList(cited_keys_);
578
579         // Initialize the drop downs
580         fillEntries(bi);
581         fillFields(bi);
582
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"]));
592
593         // Update the interface
594         updateControls(bi);
595         updateStyles(bi);
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);
603
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);
608                 int i = 0;
609                 if (cit != cmds.end())
610                         i = int(cit - cmds.begin());
611
612                 // Set the style combo appropriately
613                 citationStyleCO->blockSignals(true);
614                 citationStyleCO->setCurrentIndex(i);
615                 citationStyleCO->blockSignals(false);
616                 updateFormatting(citeStyles_[i]);
617         } else
618                 availableLV->setFocus();
619
620         applyPB->setEnabled(false);
621         okPB->setEnabled(false);
622 }
623
624
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)
629 {
630         // FIXME THREAD
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();
642         }
643         // save option for next search.
644         last_case_sensitive = case_sensitive;
645         last_reg_exp = reg_exp;
646
647         Qt::CaseSensitivity qtcase = case_sensitive ?
648                         Qt::CaseSensitive: Qt::CaseInsensitive;
649         QStringList keys;
650         // If new string (str) contains the last searched one...
651         if (!reset &&
652                 !last_searched_string.isEmpty() &&
653                 str.size() > 1 &&
654                 str.contains(last_searched_string, qtcase))
655                 // ... then only search within already found list.
656                 keys = available_model_.stringList();
657         else
658                 // ... else search all keys.
659                 keys = all_keys_;
660         // save searched string for next search.
661         last_searched_string = str;
662
663         QStringList result;
664
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);
669
670         if (str.isEmpty())
671                 result = to_qstring_list(keyVector);
672         else
673                 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
674                         qstring_to_ucs4(str), field, case_sensitive, reg_exp));
675
676         available_model_.setStringList(result);
677 }
678
679
680 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
681 {
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);
690 }
691
692
693 void GuiCitation::setCitedKeys()
694 {
695         cited_keys_ = selected_model_.stringList();
696         updateStyles();
697 }
698
699
700 bool GuiCitation::initialiseParams(string const & data)
701 {
702         InsetCommand::string2params(data, params_);
703         citeCmds_ = documentBuffer().params().citeCommands();
704         citeStyles_ = documentBuffer().params().citeStyles();
705         init();
706         return true;
707 }
708
709
710 void GuiCitation::clearParams()
711 {
712         params_.clear();
713 }
714
715
716 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
717         vector<docstring> & keyVector, docstring entry_type)
718 {
719         if (entry_type.empty())
720                 return;
721
722         vector<docstring>::iterator it = keyVector.begin();
723         vector<docstring>::iterator end = keyVector.end();
724
725         vector<docstring> result;
726         for (; it != end; ++it) {
727                 docstring const key = *it;
728                 BiblioInfo::const_iterator cit = bi.find(key);
729                 if (cit == bi.end())
730                         continue;
731                 if (cit->second.entryType() == entry_type)
732                         result.push_back(key);
733         }
734         keyVector = result;
735 }
736
737
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)
744 {
745         // Search for all chars '.|*?+(){}[^$]\'
746         // Note that '[', ']', and '\' must be escaped.
747         static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
748
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:
754         // FIXME: UNICODE
755         return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
756 #else
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:
761         // FIXME: UNICODE
762         return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
763 #endif
764 }
765
766
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)
771 {
772         vector<docstring> foundKeys;
773
774         docstring expr = trim(search_expression);
775         if (expr.empty())
776                 return foundKeys;
777
778         if (!regex)
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);
782
783         lyx::regex reg_exp;
784         try {
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
789                 // valid.
790                 LYXERR(Debug::GUI, e.what());
791                 return vector<docstring>();
792         }
793
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())
799                         continue;
800
801                 BibTeXInfo const & kvm = info->second;
802                 string data;
803                 if (only_keys)
804                         data = to_utf8(*it);
805                 else if (field.empty())
806                         data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
807                 else
808                         data = to_utf8(kvm[field]);
809
810                 if (data.empty())
811                         continue;
812
813                 try {
814                         if (lyx::regex_search(data, reg_exp))
815                                 foundKeys.push_back(*it);
816                 }
817                 catch (lyx::regex_error const & e) {
818                         LYXERR(Debug::GUI, e.what());
819                         return vector<docstring>();
820                 }
821         }
822         return foundKeys;
823 }
824
825
826 void GuiCitation::dispatchParams()
827 {
828         std::string const lfun = InsetCommand::params2string(params_);
829         dispatch(FuncRequest(getLfun(), lfun));
830 }
831
832
833 BiblioInfo const & GuiCitation::bibInfo() const
834 {
835         Buffer const & buf = documentBuffer();
836         buf.reloadBibInfoCache();
837         return buf.masterBibInfo();
838 }
839
840
841 void GuiCitation::saveSession() const
842 {
843         Dialog::saveSession();
844         QSettings settings;
845         settings.setValue(
846                 sessionKey() + "/regex", regexp_->isChecked());
847         settings.setValue(
848                 sessionKey() + "/casesensitive", casesense_->isChecked());
849         settings.setValue(
850                 sessionKey() + "/autofind", instant_->isChecked());
851         settings.setValue(
852                 sessionKey() + "/citestyle", style_);
853 }
854
855
856 void GuiCitation::restoreSession()
857 {
858         Dialog::restoreSession();
859         QSettings settings;
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();
864         updateFilterHint();
865 }
866
867
868 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
869
870
871 } // namespace frontend
872 } // namespace lyx
873
874 #include "moc_GuiCitation.cpp"
875