]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCitation.cpp
Implement CiteItem in the chain
[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         CiteItem ci;
401         ci.richtext = true;
402         QString const keytxt = toqstr(
403                 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), ci));
404         infoML->document()->setHtml(keytxt);
405 }
406
407
408 void GuiCitation::findText(QString const & text, bool reset)
409 {
410         //"All Fields" and "Keys" are the first two
411         int index = fieldsCO->currentIndex() - 2;
412         BiblioInfo const & bi = bibInfo();
413         vector<docstring> const & fields = bi.getFields();
414         docstring field;
415
416         if (index <= -1 || index >= int(fields.size()))
417                 //either "All Fields" or "Keys" or an invalid value
418                 field = from_ascii("");
419         else
420                 field = fields[index];
421
422         //Was it "Keys"?
423         bool const onlyKeys = index == -1;
424
425         //"All Entry Types" is first.
426         index = entriesCO->currentIndex() - 1;
427         vector<docstring> const & entries = bi.getEntries();
428         docstring entry_type;
429         if (index < 0 || index >= int(entries.size()))
430                 entry_type = from_ascii("");
431         else
432                 entry_type = entries[index];
433
434         bool const case_sentitive = casesense_->isChecked();
435         bool const reg_exp = regexp_->isChecked();
436
437         findKey(bi, text, onlyKeys, field, entry_type,
438                        case_sentitive, reg_exp, reset);
439         //FIXME
440         //It'd be nice to save and restore the current selection in
441         //availableLV. Currently, we get an automatic reset, since the
442         //model is reset.
443
444         updateControls(bi);
445 }
446
447
448 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
449 {
450         findText(filter_->text(), true);
451 }
452
453
454 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
455 {
456         findText(filter_->text(), true);
457 }
458
459
460 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
461 {
462         if (index >= 0 && index < citationStyleCO->count()) {
463                 vector<CitationStyle> const & styles = citeStyles_;
464                 updateFormatting(styles[index]);
465                 changed();
466         }
467 }
468
469
470 void GuiCitation::filterChanged(const QString & text)
471 {
472         if (!text.isEmpty()) {
473                 if (instant_->isChecked())
474                         findText(filter_->text());
475                 return;
476         }
477         findText(filter_->text());
478         filter_->setFocus();
479 }
480
481
482 void GuiCitation::filterPressed()
483 {
484         findText(filter_->text(), true);
485 }
486
487
488 void GuiCitation::resetFilter()
489 {
490         filter_->setText(QString());
491         findText(filter_->text(), true);
492 }
493
494
495 void GuiCitation::caseChanged()
496 {
497         findText(filter_->text());
498 }
499
500
501 void GuiCitation::regexChanged()
502 {
503         findText(filter_->text());
504 }
505
506
507 void GuiCitation::updateFilterHint()
508 {
509         QString const hint = instant_->isChecked() ?
510                 qt_("Enter string to filter the list of available citations") :
511                 qt_("Enter string to filter the list of available citations and press <Enter>");
512         filter_->setToolTip(hint);
513 }
514
515
516 void GuiCitation::instantChanged(bool checked)
517 {
518         if (checked)
519                 findText(filter_->text(), true);
520
521         updateFilterHint();
522 }
523
524
525 void GuiCitation::changed()
526 {
527         setButtons();
528 }
529
530
531 void GuiCitation::applyParams(int const choice, bool full, bool force,
532         QString before, QString after)
533 {
534         if (cited_keys_.isEmpty())
535                 return;
536
537         vector<CitationStyle> const & styles = citeStyles_;
538
539         CitationStyle cs = styles[choice];
540
541         if (!cs.textBefore)
542                 before.clear();
543         if (!cs.textAfter)
544                 after.clear();
545
546         cs.forceUpperCase &= force;
547         cs.hasStarredVersion &= full;
548         string const command = citationStyleToString(cs);
549
550         params_.setCmdName(command);
551         params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
552         params_["before"] = qstring_to_ucs4(before);
553         params_["after"] = qstring_to_ucs4(after);
554         dispatchParams();
555 }
556
557
558 void GuiCitation::clearSelection()
559 {
560         cited_keys_.clear();
561         selected_model_.setStringList(cited_keys_);
562 }
563
564
565 void GuiCitation::init()
566 {
567         // Make the list of all available bibliography keys
568         BiblioInfo const & bi = bibInfo();
569         all_keys_ = to_qstring_list(bi.getKeys());
570         available_model_.setStringList(all_keys_);
571
572         // Ditto for the keys cited in this inset
573         QString str = toqstr(params_["key"]);
574         if (str.isEmpty())
575                 cited_keys_.clear();
576         else
577                 cited_keys_ = str.split(",");
578         selected_model_.setStringList(cited_keys_);
579
580         // Initialize the drop downs
581         fillEntries(bi);
582         fillFields(bi);
583
584         // Initialize the citation formatting
585         string const & cmd = params_.getCmdName();
586         CitationStyle const cs =
587                 citationStyleFromString(cmd, documentBuffer().params());
588         forceuppercaseCB->setChecked(cs.forceUpperCase);
589         starredCB->setChecked(cs.hasStarredVersion &&
590                 documentBuffer().params().fullAuthorList());
591         textBeforeED->setText(toqstr(params_["before"]));
592         textAfterED->setText(toqstr(params_["after"]));
593
594         // Update the interface
595         updateControls(bi);
596         updateStyles(bi);
597         if (selected_model_.rowCount()) {
598                 selectedLV->blockSignals(true);
599                 selectedLV->setFocus();
600                 QModelIndex idx = selected_model_.index(0, 0);
601                 selectedLV->selectionModel()->select(idx,
602                                 QItemSelectionModel::ClearAndSelect);
603                 selectedLV->blockSignals(false);
604
605                 // Find the citation style
606                 vector<string> const & cmds = citeCmds_;
607                 vector<string>::const_iterator cit =
608                         std::find(cmds.begin(), cmds.end(), cs.name);
609                 int i = 0;
610                 if (cit != cmds.end())
611                         i = int(cit - cmds.begin());
612
613                 // Set the style combo appropriately
614                 citationStyleCO->blockSignals(true);
615                 citationStyleCO->setCurrentIndex(i);
616                 citationStyleCO->blockSignals(false);
617                 updateFormatting(citeStyles_[i]);
618         } else
619                 availableLV->setFocus();
620
621         applyPB->setEnabled(false);
622         okPB->setEnabled(false);
623 }
624
625
626 void GuiCitation::findKey(BiblioInfo const & bi,
627         QString const & str, bool only_keys,
628         docstring field, docstring entry_type,
629         bool case_sensitive, bool reg_exp, bool reset)
630 {
631         // FIXME THREAD
632         // This should be moved to a class member.
633         // Used for optimisation: store last searched string.
634         static QString last_searched_string;
635         // Used to disable the above optimisation.
636         static bool last_case_sensitive;
637         static bool last_reg_exp;
638         // Reset last_searched_string in case of changed option.
639         if (last_case_sensitive != case_sensitive
640                 || last_reg_exp != reg_exp) {
641                         LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
642                 last_searched_string.clear();
643         }
644         // save option for next search.
645         last_case_sensitive = case_sensitive;
646         last_reg_exp = reg_exp;
647
648         Qt::CaseSensitivity qtcase = case_sensitive ?
649                         Qt::CaseSensitive: Qt::CaseInsensitive;
650         QStringList keys;
651         // If new string (str) contains the last searched one...
652         if (!reset &&
653                 !last_searched_string.isEmpty() &&
654                 str.size() > 1 &&
655                 str.contains(last_searched_string, qtcase))
656                 // ... then only search within already found list.
657                 keys = available_model_.stringList();
658         else
659                 // ... else search all keys.
660                 keys = all_keys_;
661         // save searched string for next search.
662         last_searched_string = str;
663
664         QStringList result;
665
666         // First, filter by entry_type, which will be faster than
667         // what follows, so we may get to do that on less.
668         vector<docstring> keyVector = to_docstring_vector(keys);
669         filterByEntryType(bi, keyVector, entry_type);
670
671         if (str.isEmpty())
672                 result = to_qstring_list(keyVector);
673         else
674                 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
675                         qstring_to_ucs4(str), field, case_sensitive, reg_exp));
676
677         available_model_.setStringList(result);
678 }
679
680
681 QStringList GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
682 {
683         vector<docstring> const keys = to_docstring_vector(cited_keys_);
684         vector<CitationStyle> styles = citeStyles_;
685         CiteItem ci;
686         ci.textBefore = qstring_to_ucs4(textBeforeED->text());
687         ci.textAfter = qstring_to_ucs4(textAfterED->text());
688         ci.context = CiteItem::Dialog;
689         ci.max_size = max_size;
690         vector<docstring> ret = bi.getCiteStrings(keys, styles, documentBuffer(), ci);
691         return to_qstring_list(ret);
692 }
693
694
695 void GuiCitation::setCitedKeys()
696 {
697         cited_keys_ = selected_model_.stringList();
698         updateStyles();
699 }
700
701
702 bool GuiCitation::initialiseParams(string const & data)
703 {
704         InsetCommand::string2params(data, params_);
705         citeCmds_ = documentBuffer().params().citeCommands();
706         citeStyles_ = documentBuffer().params().citeStyles();
707         init();
708         return true;
709 }
710
711
712 void GuiCitation::clearParams()
713 {
714         params_.clear();
715 }
716
717
718 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
719         vector<docstring> & keyVector, docstring entry_type)
720 {
721         if (entry_type.empty())
722                 return;
723
724         vector<docstring>::iterator it = keyVector.begin();
725         vector<docstring>::iterator end = keyVector.end();
726
727         vector<docstring> result;
728         for (; it != end; ++it) {
729                 docstring const key = *it;
730                 BiblioInfo::const_iterator cit = bi.find(key);
731                 if (cit == bi.end())
732                         continue;
733                 if (cit->second.entryType() == entry_type)
734                         result.push_back(key);
735         }
736         keyVector = result;
737 }
738
739
740 // Escape special chars.
741 // All characters are literals except: '.|*?+(){}[]^$\'
742 // These characters are literals when preceded by a "\", which is done here
743 // @todo: This function should be moved to support, and then the test in tests
744 //        should be moved there as well.
745 static docstring escape_special_chars(docstring const & expr)
746 {
747         // Search for all chars '.|*?+(){}[^$]\'
748         // Note that '[', ']', and '\' must be escaped.
749         static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
750
751         // $& is an ECMAScript format expression that expands to all
752         // of the current match
753 #ifdef LYX_USE_STD_REGEX
754         // To prefix a matched expression with a single literal backslash, we
755         // need to escape it for the C++ compiler and use:
756         // FIXME: UNICODE
757         return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
758 #else
759         // A backslash in the format string starts an escape sequence in boost.
760         // Thus, to prefix a matched expression with a single literal backslash,
761         // we need to give two backslashes to the regex engine, and escape both
762         // for the C++ compiler and use:
763         // FIXME: UNICODE
764         return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
765 #endif
766 }
767
768
769 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
770         vector<docstring> const & keys_to_search, bool only_keys,
771         docstring const & search_expression, docstring field,
772         bool case_sensitive, bool regex)
773 {
774         vector<docstring> foundKeys;
775
776         docstring expr = trim(search_expression);
777         if (expr.empty())
778                 return foundKeys;
779
780         if (!regex)
781                 // We must escape special chars in the search_expr so that
782                 // it is treated as a simple string by lyx::regex.
783                 expr = escape_special_chars(expr);
784
785         lyx::regex reg_exp;
786         try {
787                 reg_exp.assign(to_utf8(expr), case_sensitive ?
788                         lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
789         } catch (lyx::regex_error const & e) {
790                 // lyx::regex throws an exception if the regular expression is not
791                 // valid.
792                 LYXERR(Debug::GUI, e.what());
793                 return vector<docstring>();
794         }
795
796         vector<docstring>::const_iterator it = keys_to_search.begin();
797         vector<docstring>::const_iterator end = keys_to_search.end();
798         for (; it != end; ++it ) {
799                 BiblioInfo::const_iterator info = bi.find(*it);
800                 if (info == bi.end())
801                         continue;
802
803                 BibTeXInfo const & kvm = info->second;
804                 string data;
805                 if (only_keys)
806                         data = to_utf8(*it);
807                 else if (field.empty())
808                         data = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
809                 else
810                         data = to_utf8(kvm[field]);
811
812                 if (data.empty())
813                         continue;
814
815                 try {
816                         if (lyx::regex_search(data, reg_exp))
817                                 foundKeys.push_back(*it);
818                 }
819                 catch (lyx::regex_error const & e) {
820                         LYXERR(Debug::GUI, e.what());
821                         return vector<docstring>();
822                 }
823         }
824         return foundKeys;
825 }
826
827
828 void GuiCitation::dispatchParams()
829 {
830         std::string const lfun = InsetCommand::params2string(params_);
831         dispatch(FuncRequest(getLfun(), lfun));
832 }
833
834
835 BiblioInfo const & GuiCitation::bibInfo() const
836 {
837         Buffer const & buf = documentBuffer();
838         buf.reloadBibInfoCache();
839         return buf.masterBibInfo();
840 }
841
842
843 void GuiCitation::saveSession() const
844 {
845         Dialog::saveSession();
846         QSettings settings;
847         settings.setValue(
848                 sessionKey() + "/regex", regexp_->isChecked());
849         settings.setValue(
850                 sessionKey() + "/casesensitive", casesense_->isChecked());
851         settings.setValue(
852                 sessionKey() + "/autofind", instant_->isChecked());
853         settings.setValue(
854                 sessionKey() + "/citestyle", style_);
855 }
856
857
858 void GuiCitation::restoreSession()
859 {
860         Dialog::restoreSession();
861         QSettings settings;
862         regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
863         casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
864         instant_->setChecked(settings.value(sessionKey() + "/autofind").toBool());
865         style_ = settings.value(sessionKey() + "/citestyle").toInt();
866         updateFilterHint();
867 }
868
869
870 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
871
872
873 } // namespace frontend
874 } // namespace lyx
875
876 #include "moc_GuiCitation.cpp"
877