]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiCitation.cpp
Respect "literal" setting when entering citation via LyX server.
[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 "qt_helpers.h"
22
23 #include "Buffer.h"
24 #include "BufferView.h"
25 #include "BiblioInfo.h"
26 #include "BufferParams.h"
27 #include "TextClass.h"
28 #include "FuncRequest.h"
29
30 #include "insets/InsetCitation.h"
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 <QStandardItemModel>
43 #include <QVariant>
44
45 #include <vector>
46 #include <string>
47
48 #undef KeyPress
49
50 #include "support/regex.h"
51
52 #include <algorithm>
53 #include <string>
54 #include <vector>
55
56 using namespace std;
57 using namespace lyx::support;
58
59 namespace lyx {
60 namespace frontend {
61
62 // FIXME THREAD
63 // I am guessing that it would not hurt to make these private members.
64 static vector<string> citeCmds_;
65 static vector<CitationStyle> citeStyles_;
66
67
68 template<typename String>
69 static QStringList to_qstring_list(vector<String> const & v)
70 {
71         QStringList qlist;
72
73         for (size_t i = 0; i != v.size(); ++i) {
74                 if (v[i].empty())
75                         continue;
76                 qlist.append(lyx::toqstr(v[i]));
77         }
78         return qlist;
79 }
80
81
82 static vector<lyx::docstring> to_docstring_vector(QStringList const & qlist)
83 {
84         vector<lyx::docstring> v;
85         for (int i = 0; i != qlist.size(); ++i) {
86                 if (qlist[i].isEmpty())
87                         continue;
88                 v.push_back(lyx::qstring_to_ucs4(qlist[i]));
89         }
90         return v;
91 }
92
93
94 GuiCitation::GuiCitation(GuiView & lv)
95         : DialogView(lv, "citation", qt_("Citation")),
96           style_(QString()), params_(insetCode("citation"))
97 {
98         setupUi(this);
99
100         // The filter bar
101         filter_ = new FancyLineEdit(this);
102         filter_->setButtonPixmap(FancyLineEdit::Right, getPixmap("images/", "editclear", "svgz,png"));
103         filter_->setButtonVisible(FancyLineEdit::Right, true);
104         filter_->setButtonToolTip(FancyLineEdit::Right, qt_("Clear text"));
105         filter_->setAutoHideButton(FancyLineEdit::Right, true);
106         filter_->setPlaceholderText(qt_("All avail. citations"));
107
108         filterBarL->addWidget(filter_, 0);
109         findKeysLA->setBuddy(filter_);
110
111         // Add search options as button menu
112         regexp_ = new QAction(qt_("Regular e&xpression"), this);
113         regexp_->setCheckable(true);
114         casesense_ = new QAction(qt_("Case se&nsitive"), this);
115         casesense_->setCheckable(true);
116         instant_ = new QAction(qt_("Search as you &type"), this);
117         instant_->setCheckable(true);
118         instant_->setChecked(true);
119
120         QMenu * searchOpts = new QMenu(this);
121         searchOpts->addAction(regexp_);
122         searchOpts->addAction(casesense_);
123         searchOpts->addAction(instant_);
124         searchOptionsPB->setMenu(searchOpts);
125
126         connect(citationStyleCO, SIGNAL(activated(int)),
127                 this, SLOT(on_citationStyleCO_currentIndexChanged(int)));
128         connect(starredCB, SIGNAL(clicked()),
129                 this, SLOT(updateStyles()));
130         connect(literalCB, SIGNAL(clicked()),
131                 this, SLOT(changed()));
132         connect(forceuppercaseCB, SIGNAL(clicked()),
133                 this, SLOT(updateStyles()));
134         connect(textBeforeED, SIGNAL(textChanged(QString)),
135                 this, SLOT(updateStyles()));
136         connect(textAfterED, SIGNAL(textChanged(QString)),
137                 this, SLOT(updateStyles()));
138         connect(textBeforeED, SIGNAL(returnPressed()),
139                 this, SLOT(on_okPB_clicked()));
140         connect(textAfterED, SIGNAL(returnPressed()),
141                 this, SLOT(on_okPB_clicked()));
142
143         selectionManager = new GuiSelectionManager(this, availableLV, selectedLV,
144                         addPB, deletePB, upPB, downPB, &available_model_, &selected_model_, 1);
145         connect(selectionManager, SIGNAL(selectionChanged()),
146                 this, SLOT(setCitedKeys()));
147         connect(selectionManager, SIGNAL(updateHook()),
148                 this, SLOT(updateControls()));
149         connect(selectionManager, SIGNAL(okHook()),
150                 this, SLOT(on_okPB_clicked()));
151
152         connect(filter_, SIGNAL(rightButtonClicked()),
153                 this, SLOT(resetFilter()));
154         connect(filter_, SIGNAL(textEdited(QString)),
155                 this, SLOT(filterChanged(QString)));
156         connect(filter_, SIGNAL(returnPressed()),
157                 this, SLOT(filterPressed()));
158 #if (QT_VERSION < 0x050000)
159         connect(filter_, SIGNAL(downPressed()),
160                 availableLV, SLOT(setFocus()));
161 #else
162         connect(filter_, &FancyLineEdit::downPressed,
163                 availableLV, [=](){ focusAndHighlight(availableLV); });
164 #endif
165         connect(regexp_, SIGNAL(triggered()),
166                 this, SLOT(regexChanged()));
167         connect(casesense_, SIGNAL(triggered()),
168                 this, SLOT(caseChanged()));
169         connect(instant_, SIGNAL(triggered(bool)),
170                 this, SLOT(instantChanged(bool)));
171
172 #if (QT_VERSION < 0x050000)
173         selectedLV->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
174 #else
175         selectedLV->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
176 #endif
177
178         setFocusProxy(filter_);
179 }
180
181
182 void GuiCitation::closeEvent(QCloseEvent * e)
183 {
184         clearSelection();
185         DialogView::closeEvent(e);
186 }
187
188
189 void GuiCitation::applyView()
190 {
191         int const choice = max(0, citationStyleCO->currentIndex());
192         style_ = citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
193         bool const full  = starredCB->isChecked();
194         bool const force = forceuppercaseCB->isChecked();
195
196         QString const before = textBeforeED->text();
197         QString const after = textAfterED->text();
198
199         applyParams(choice, full, force, before, after);
200 }
201
202
203 void GuiCitation::showEvent(QShowEvent * e)
204 {
205         filter_->clear();
206         availableLV->setFocus();
207         DialogView::showEvent(e);
208 }
209
210
211 void GuiCitation::on_okPB_clicked()
212 {
213         applyView();
214         clearSelection();
215         hide();
216 }
217
218
219 void GuiCitation::on_cancelPB_clicked()
220 {
221         clearSelection();
222         hide();
223 }
224
225
226 void GuiCitation::on_applyPB_clicked()
227 {
228         applyView();
229 }
230
231
232 void GuiCitation::on_restorePB_clicked()
233 {
234         init();
235         updateFilterHint();
236 }
237
238
239 void GuiCitation::on_literalCB_clicked()
240 {
241         InsetCitation::last_literal = literalCB->isChecked();
242         changed();
243 }
244
245
246 void GuiCitation::updateControls()
247 {
248         BiblioInfo const & bi = bibInfo();
249         updateControls(bi);
250 }
251
252
253 // The main point of separating this out is that the fill*() methods
254 // called in update() do not need to be called for INTERNAL updates,
255 // such as when addPB is pressed, as the list of fields, entries, etc,
256 // will not have changed.
257 void GuiCitation::updateControls(BiblioInfo const & bi)
258 {
259         QModelIndex idx = selectionManager->getSelectedIndex(1);
260         updateInfo(bi, idx);
261         int i = citationStyleCO->currentIndex();
262         if (i == -1 || i > int(citeStyles_.size()))
263                 i = 0;
264         updateFormatting(citeStyles_[i]);
265         selectionManager->update();
266 }
267
268
269 void GuiCitation::updateFormatting(CitationStyle const & currentStyle)
270 {
271         BufferParams const bp = documentBuffer().params();
272         bool const force = currentStyle.forceUpperCase;
273         bool const starred = currentStyle.hasStarredVersion;
274         bool const full = starred && bp.fullAuthorList();
275         bool const textbefore = currentStyle.textBefore;
276         bool const textafter = currentStyle.textAfter;
277
278         int const rows = selectedLV->model()->rowCount();
279
280         bool const qualified = currentStyle.hasQualifiedList
281                 && (rows > 1
282                     || !params_["pretextlist"].empty()
283                     || !params_["posttextlist"].empty());
284         selectedLV->horizontalHeader()->setVisible(qualified);
285         selectedLV->setColumnHidden(0, !qualified);
286         selectedLV->setColumnHidden(2, !qualified);
287         bool const haveSelection = rows > 0;
288         if (qualified) {
289                 textBeforeLA->setText(qt_("General text befo&re:"));
290                 textAfterLA->setText(qt_("General &text after:"));
291                 textBeforeED->setToolTip(qt_("Text that precedes the whole reference list. "
292                                              "For text that precedes individual items, "
293                                              "double-click on the respective entry above."));
294                 textAfterLA->setToolTip(qt_("General &text after:"));
295                 textAfterED->setToolTip(qt_("Text that follows the whole reference list. "
296                                              "For text that follows individual items, "
297                                              "double-click on the respective entry above."));
298         } else {
299                 textBeforeLA->setText(qt_("Text befo&re:"));
300                 if (textbefore && haveSelection)
301                         textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\")"));
302                 else
303                         textBeforeED->setToolTip(qt_("Text that precedes the reference (e.g., \"cf.\"), "
304                                                      "if the current citation style supports this."));
305                 textAfterLA->setText(qt_("&Text after:"));
306                 if (textafter && haveSelection)
307                         textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages)"));
308                 else
309                         textAfterED->setToolTip(qt_("Text that follows the reference (e.g., pages), "
310                                                     "if the current citation style supports this."));
311         }
312
313         forceuppercaseCB->setEnabled(force && haveSelection);
314         if (force && haveSelection)
315                 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\")."));
316         else
317                 forceuppercaseCB->setToolTip(qt_("Force upper case in names (\"Del Piero\", not \"del Piero\"), "
318                                              "if the current citation style supports this."));
319         starredCB->setEnabled(full && haveSelection);
320         textBeforeED->setEnabled(textbefore && haveSelection);
321         textBeforeLA->setEnabled(textbefore && haveSelection);
322         textAfterED->setEnabled(textafter && haveSelection);
323         textAfterLA->setEnabled(textafter && haveSelection);
324         literalCB->setEnabled(textbefore || textafter);
325         citationStyleCO->setEnabled(haveSelection);
326         citationStyleLA->setEnabled(haveSelection);
327
328         // Check if we have a custom string/tooltip for the starred version
329         if (starred && !currentStyle.stardesc.empty()) {
330                 string val =
331                         bp.documentClass().getCiteMacro(bp.citeEngineType(), currentStyle.stardesc);
332                 docstring guistring;
333                 if (!val.empty()) {
334                         guistring = translateIfPossible(from_utf8(val));
335                         starredCB->setText(toqstr(guistring));
336                         starredCB->setEnabled(haveSelection);
337                 }
338                 if (!currentStyle.startooltip.empty()) {
339                         val = bp.documentClass().getCiteMacro(bp.citeEngineType(),
340                                                               currentStyle.startooltip);
341                         if (!val.empty())
342                                 guistring = translateIfPossible(from_utf8(val));
343                 }
344                 // Tooltip might also be empty
345                 starredCB->setToolTip(toqstr(guistring));
346         } else {
347                 // This is the default meaning of the starred commands
348                 starredCB->setText(qt_("All aut&hors"));
349                 if (full && haveSelection)
350                         starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\")"));
351                 else
352                         starredCB->setToolTip(qt_("Always list all authors (rather than using \"et al.\"), "
353                                                   "if the current citation style supports this."));
354         }
355 }
356
357
358 // Update the styles for the style combo, citationStyleCO, and mark the
359 // settings as changed. Called upon changing the cited keys (including
360 // merely reordering the keys) or editing the text before/after fields.
361 void GuiCitation::updateStyles()
362 {
363         BiblioInfo const & bi = bibInfo();
364         updateStyles(bi);
365         changed();
366 }
367
368
369 // Update the styles for the style combo, citationStyleCO.
370 void GuiCitation::updateStyles(BiblioInfo const & bi)
371 {
372         QStringList selected_keys = selectedKeys();
373         int curr = selectedLV->model()->rowCount() - 1;
374
375         if (curr < 0 || selected_keys.empty()) {
376                 citationStyleCO->clear();
377                 citationStyleCO->setEnabled(false);
378                 citationStyleLA->setEnabled(false);
379                 return;
380         }
381
382         static const size_t max_length = 80;
383         BiblioInfo::CiteStringMap sty = citationStyles(bi, max_length);
384
385         if (sty.empty()) {
386                 // some error
387                 citationStyleCO->setEnabled(false);
388                 citationStyleLA->setEnabled(false);
389                 citationStyleCO->clear();
390                 return;
391         }
392
393         citationStyleCO->blockSignals(true);
394
395         // save old style selection
396         QString const curdata =
397                 citationStyleCO->itemData(citationStyleCO->currentIndex()).toString();
398         QString const olddata = (curdata.isEmpty()) ? style_ : curdata;
399         citationStyleCO->clear();
400         BiblioInfo::CiteStringMap::const_iterator cit = sty.begin();
401         BiblioInfo::CiteStringMap::const_iterator end = sty.end();
402         for (int ii = 1; cit != end; ++cit, ++ii)
403                 citationStyleCO->addItem(toqstr(cit->second), toqstr(cit->first));
404         citationStyleCO->setEnabled(true);
405         citationStyleLA->setEnabled(true);
406         // restore old style selection
407         int const i = citationStyleCO->findData(olddata);
408         if (i != -1)
409                 citationStyleCO->setCurrentIndex(i);
410
411         citationStyleCO->blockSignals(false);
412 }
413
414
415 void GuiCitation::fillFields(BiblioInfo const & bi)
416 {
417         fieldsCO->blockSignals(true);
418         int const oldIndex = fieldsCO->currentIndex();
419         fieldsCO->clear();
420         QStringList const fields = to_qstring_list(bi.getFields());
421         fieldsCO->insertItem(0, qt_("All fields"));
422         fieldsCO->insertItem(1, qt_("Keys"));
423         fieldsCO->insertItems(2, fields);
424         if (oldIndex != -1 && oldIndex < fieldsCO->count())
425                 fieldsCO->setCurrentIndex(oldIndex);
426         fieldsCO->blockSignals(false);
427 }
428
429
430 void GuiCitation::fillEntries(BiblioInfo const & bi)
431 {
432         entriesCO->blockSignals(true);
433         int const oldIndex = entriesCO->currentIndex();
434         entriesCO->clear();
435         QStringList const entries = to_qstring_list(bi.getEntries());
436         entriesCO->insertItem(0, qt_("All entry types"));
437         entriesCO->insertItems(1, entries);
438         if (oldIndex != -1 && oldIndex < entriesCO->count())
439                 entriesCO->setCurrentIndex(oldIndex);
440         entriesCO->blockSignals(false);
441 }
442
443
444 bool GuiCitation::isSelected(QModelIndex const & idx)
445 {
446         QString const str = idx.data().toString();
447         return selectedKeys().contains(str);
448 }
449
450
451 void GuiCitation::setButtons()
452 {
453         int const srows = selectedLV->model()->rowCount();
454         applyPB->setEnabled(srows > 0);
455         okPB->setEnabled(srows > 0);
456 }
457
458
459 void GuiCitation::updateInfo(BiblioInfo const & bi, QModelIndex const & idx)
460 {
461         if (!idx.isValid() || bi.empty()) {
462                 infoML->document()->clear();
463                 infoML->setToolTip(qt_("Displays a sketchy preview if a citation is selected above"));
464                 return;
465         }
466
467         infoML->setToolTip(qt_("Sketchy preview of the selected citation"));
468         CiteItem ci;
469         ci.richtext = true;
470         QString const keytxt = toqstr(
471                 bi.getInfo(qstring_to_ucs4(idx.data().toString()), documentBuffer(), ci));
472         infoML->document()->setHtml(keytxt);
473 }
474
475
476 void GuiCitation::findText(QString const & text, bool reset)
477 {
478         //"All Fields" and "Keys" are the first two
479         int index = fieldsCO->currentIndex() - 2;
480         BiblioInfo const & bi = bibInfo();
481         vector<docstring> const & fields = bi.getFields();
482         docstring field;
483
484         if (index <= -1 || index >= int(fields.size()))
485                 //either "All Fields" or "Keys" or an invalid value
486                 field = from_ascii("");
487         else
488                 field = fields[index];
489
490         //Was it "Keys"?
491         bool const onlyKeys = index == -1;
492
493         //"All Entry Types" is first.
494         index = entriesCO->currentIndex() - 1;
495         vector<docstring> const & entries = bi.getEntries();
496         docstring entry_type;
497         if (index < 0 || index >= int(entries.size()))
498                 entry_type = from_ascii("");
499         else
500                 entry_type = entries[index];
501
502         bool const case_sentitive = casesense_->isChecked();
503         bool const reg_exp = regexp_->isChecked();
504
505         findKey(bi, text, onlyKeys, field, entry_type,
506                        case_sentitive, reg_exp, reset);
507         //FIXME
508         //It'd be nice to save and restore the current selection in
509         //availableLV. Currently, we get an automatic reset, since the
510         //model is reset.
511
512         updateControls(bi);
513 }
514
515
516 void GuiCitation::on_fieldsCO_currentIndexChanged(int /*index*/)
517 {
518         findText(filter_->text(), true);
519 }
520
521
522 void GuiCitation::on_entriesCO_currentIndexChanged(int /*index*/)
523 {
524         findText(filter_->text(), true);
525 }
526
527
528 void GuiCitation::on_citationStyleCO_currentIndexChanged(int index)
529 {
530         if (index >= 0 && index < citationStyleCO->count()) {
531                 vector<CitationStyle> const & styles = citeStyles_;
532                 updateFormatting(styles[index]);
533                 changed();
534         }
535 }
536
537
538 void GuiCitation::filterChanged(const QString & text)
539 {
540         if (!text.isEmpty()) {
541                 if (instant_->isChecked())
542                         findText(filter_->text());
543                 return;
544         }
545         findText(filter_->text());
546         filter_->setFocus();
547 }
548
549
550 void GuiCitation::filterPressed()
551 {
552         findText(filter_->text(), true);
553 }
554
555
556 void GuiCitation::resetFilter()
557 {
558         filter_->setText(QString());
559         findText(filter_->text(), true);
560 }
561
562
563 void GuiCitation::caseChanged()
564 {
565         findText(filter_->text());
566 }
567
568
569 void GuiCitation::regexChanged()
570 {
571         findText(filter_->text());
572 }
573
574
575 void GuiCitation::updateFilterHint()
576 {
577         QString const hint = instant_->isChecked() ?
578                 qt_("Enter string to filter the list of available citations") :
579                 qt_("Enter string to filter the list of available citations and press <Enter>");
580         filter_->setToolTip(hint);
581 }
582
583
584 void GuiCitation::instantChanged(bool checked)
585 {
586         if (checked)
587                 findText(filter_->text(), true);
588
589         updateFilterHint();
590 }
591
592
593 void GuiCitation::changed()
594 {
595         setButtons();
596 }
597
598
599 void GuiCitation::applyParams(int const choice, bool full, bool force,
600         QString before, QString after)
601 {
602         if (cited_keys_.isEmpty())
603                 return;
604
605         vector<CitationStyle> const & styles = citeStyles_;
606
607         CitationStyle cs = styles[choice];
608
609         if (!cs.textBefore)
610                 before.clear();
611         if (!cs.textAfter)
612                 after.clear();
613
614         cs.forceUpperCase &= force;
615         cs.hasStarredVersion &= full;
616         string const command = citationStyleToString(cs);
617
618         params_.setCmdName(command);
619         params_["key"] = qstring_to_ucs4(cited_keys_.join(","));
620         params_["before"] = qstring_to_ucs4(before);
621         params_["after"] = qstring_to_ucs4(after);
622         if (cs.hasQualifiedList) {
623                 params_["pretextlist"] = getStringFromVector(getPreTexts(), from_ascii("\t"));
624                 params_["posttextlist"] = getStringFromVector(getPostTexts(), from_ascii("\t"));
625         }
626         params_["literal"] = literalCB->isChecked() ? from_ascii("true") : from_ascii("false");
627         dispatchParams();
628 }
629
630
631 void GuiCitation::clearSelection()
632 {
633         cited_keys_.clear();
634         setSelectedKeys(cited_keys_);
635 }
636
637
638 void GuiCitation::setSelectedKeys(QStringList const sl)
639 {
640         selected_model_.clear();
641         selected_model_.setColumnCount(3);
642         QStringList headers;
643         headers << qt_("Text before")
644                 << qt_("Cite key")
645                 << qt_("Text after");
646         selected_model_.setHorizontalHeaderLabels(headers);
647         selectedLV->setColumnHidden(0, true);
648         selectedLV->setColumnHidden(2, true);
649         selectedLV->verticalHeader()->setVisible(false);
650         selectedLV->horizontalHeader()->setVisible(false);
651         QStringList::const_iterator it  = sl.begin();
652         QStringList::const_iterator end = sl.end();
653         for (int i = 0; it != end; ++it, ++i) {
654                 QStandardItem * si = new QStandardItem();
655                 si->setData(*it);
656                 si->setText(*it);
657                 si->setToolTip(*it);
658                 si->setEditable(false);
659                 selected_model_.setItem(i, 1, si);
660         }
661 }
662
663
664 QStringList GuiCitation::selectedKeys()
665 {
666         QStringList res;
667         for (int i = 0; i != selected_model_.rowCount(); ++i) {
668                 QStandardItem const * item = selected_model_.item(i, 1);
669                 if (item)
670                         res.append(item->text());
671         }
672         return res;
673 }
674
675
676 void GuiCitation::setPreTexts(vector<docstring> const m)
677 {
678         for (docstring const & s: m) {
679                 QStandardItem * si = new QStandardItem();
680                 docstring key;
681                 docstring pre = split(s, key, ' ');
682                 si->setData(toqstr(pre));
683                 si->setText(toqstr(pre));
684                 QModelIndexList qmil =
685                                 selected_model_.match(selected_model_.index(0, 1),
686                                                      Qt::DisplayRole, toqstr(key), 1,
687                                                      Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
688                 if (!qmil.empty())
689                         selected_model_.setItem(qmil.front().row(), 0, si);
690         }
691 }
692
693
694 vector<docstring> GuiCitation::getPreTexts()
695 {
696         vector<docstring> res;
697         for (int i = 0; i != selected_model_.rowCount(); ++i) {
698                 QStandardItem const * key = selected_model_.item(i, 1);
699                 QStandardItem const * pre = selected_model_.item(i, 0);
700                 if (key && pre && !key->text().isEmpty() && !pre->text().isEmpty())
701                         res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(pre->text()));
702         }
703         return res;
704 }
705
706
707 void GuiCitation::setPostTexts(vector<docstring> const m)
708 {
709         for (docstring const & s: m) {
710                 QStandardItem * si = new QStandardItem();
711                 docstring key;
712                 docstring post = split(s, key, ' ');
713                 si->setData(toqstr(post));
714                 si->setText(toqstr(post));
715                 QModelIndexList qmil =
716                                 selected_model_.match(selected_model_.index(0, 1),
717                                                      Qt::DisplayRole, toqstr(key), 1,
718                                                      Qt::MatchFlags(Qt::MatchExactly | Qt::MatchWrap));
719                 if (!qmil.empty())
720                         selected_model_.setItem(qmil.front().row(), 2, si);
721         }
722 }
723
724
725 vector<docstring> GuiCitation::getPostTexts()
726 {
727         vector<docstring> res;
728         for (int i = 0; i != selected_model_.rowCount(); ++i) {
729                 QStandardItem const * key = selected_model_.item(i, 1);
730                 QStandardItem const * post = selected_model_.item(i, 2);
731                 if (key && post)
732                         res.push_back(qstring_to_ucs4(key->text()) + " " + qstring_to_ucs4(post->text()));
733         }
734         return res;
735 }
736
737
738 void GuiCitation::init()
739 {
740         // Make the list of all available bibliography keys
741         BiblioInfo const & bi = bibInfo();
742         all_keys_ = to_qstring_list(bi.getKeys());
743
744         available_model_.setStringList(all_keys_);
745
746         // Ditto for the keys cited in this inset
747         QString str = toqstr(params_["key"]);
748         if (str.isEmpty())
749                 cited_keys_.clear();
750         else
751                 cited_keys_ = str.split(",");
752         setSelectedKeys(cited_keys_);
753
754         // Initialize the drop downs
755         fillEntries(bi);
756         fillFields(bi);
757
758         // Initialize the citation formatting
759         string const & cmd = params_.getCmdName();
760         CitationStyle const cs =
761                 citationStyleFromString(cmd, documentBuffer().params());
762
763         forceuppercaseCB->setChecked(cs.forceUpperCase);
764         starredCB->setChecked(cs.hasStarredVersion &&
765                 documentBuffer().params().fullAuthorList());
766         textBeforeED->setText(toqstr(params_["before"]));
767         textAfterED->setText(toqstr(params_["after"]));
768
769         // if this is a new citation, we set the literal checkbox
770         // to its last set value.
771         if (cited_keys_.isEmpty())
772                 literalCB->setChecked(InsetCitation::last_literal);
773         else
774                 literalCB->setChecked(params_["literal"] == "true");
775
776         setPreTexts(getVectorFromString(params_["pretextlist"], from_ascii("\t")));
777         setPostTexts(getVectorFromString(params_["posttextlist"], from_ascii("\t")));
778
779         // Update the interface
780         updateControls(bi);
781         updateStyles(bi);
782         if (selected_model_.rowCount()) {
783                 selectedLV->blockSignals(true);
784                 selectedLV->setFocus();
785                 selectedLV->selectRow(0);
786                 selectedLV->blockSignals(false);
787
788                 // Find the citation style
789                 vector<string> const & cmds = citeCmds_;
790                 vector<string>::const_iterator cit =
791                         std::find(cmds.begin(), cmds.end(), cs.name);
792                 int i = 0;
793                 if (cit != cmds.end())
794                         i = int(cit - cmds.begin());
795
796                 // Set the style combo appropriately
797                 citationStyleCO->blockSignals(true);
798                 citationStyleCO->setCurrentIndex(i);
799                 citationStyleCO->blockSignals(false);
800                 updateFormatting(citeStyles_[i]);
801         } else
802                 availableLV->setFocus();
803
804         applyPB->setEnabled(false);
805         okPB->setEnabled(false);
806 }
807
808
809 void GuiCitation::findKey(BiblioInfo const & bi,
810         QString const & str, bool only_keys,
811         docstring field, docstring entry_type,
812         bool case_sensitive, bool reg_exp, bool reset)
813 {
814         // FIXME THREAD
815         // This should be moved to a class member.
816         // Used for optimisation: store last searched string.
817         static QString last_searched_string;
818         // Used to disable the above optimisation.
819         static bool last_case_sensitive;
820         static bool last_reg_exp;
821         // Reset last_searched_string in case of changed option.
822         if (last_case_sensitive != case_sensitive
823                 || last_reg_exp != reg_exp) {
824                         LYXERR(Debug::GUI, "GuiCitation::findKey: optimisation disabled!");
825                 last_searched_string.clear();
826         }
827         // save option for next search.
828         last_case_sensitive = case_sensitive;
829         last_reg_exp = reg_exp;
830
831         Qt::CaseSensitivity qtcase = case_sensitive ?
832                         Qt::CaseSensitive: Qt::CaseInsensitive;
833         QStringList keys;
834         // If new string (str) contains the last searched one...
835         if (!reset &&
836                 !last_searched_string.isEmpty() &&
837                 str.size() > 1 &&
838                 str.contains(last_searched_string, qtcase))
839                 // ... then only search within already found list.
840                 keys = available_model_.stringList();
841         else
842                 // ... else search all keys.
843                 keys = all_keys_;
844         // save searched string for next search.
845         last_searched_string = str;
846
847         QStringList result;
848
849         // First, filter by entry_type, which will be faster than
850         // what follows, so we may get to do that on less.
851         vector<docstring> keyVector = to_docstring_vector(keys);
852         filterByEntryType(bi, keyVector, entry_type);
853
854         if (str.isEmpty())
855                 result = to_qstring_list(keyVector);
856         else
857                 result = to_qstring_list(searchKeys(bi, keyVector, only_keys,
858                         qstring_to_ucs4(str), field, case_sensitive, reg_exp));
859
860         available_model_.setStringList(result);
861 }
862
863
864 BiblioInfo::CiteStringMap GuiCitation::citationStyles(BiblioInfo const & bi, size_t max_size)
865 {
866         vector<docstring> const keys = to_docstring_vector(cited_keys_);
867         vector<CitationStyle> styles = citeStyles_;
868         int ind = citationStyleCO->currentIndex();
869         if (ind == -1)
870                 ind = 0;
871         CitationStyle cs = styles[ind];
872         vector<docstring> pretexts = getPreTexts();
873         vector<docstring> posttexts = getPostTexts();
874         bool const qualified = cs.hasQualifiedList
875                 && (selectedLV->model()->rowCount() > 1
876                     || !pretexts.empty()
877                     || !posttexts.empty());
878         std::map<docstring, docstring> pres;
879         for (docstring const & s: pretexts) {
880                 docstring key;
881                 docstring val = split(s, key, ' ');
882                 pres[key] = val;
883         }
884         std::map<docstring, docstring> posts;
885         for (docstring const & s: posttexts) {
886                 docstring key;
887                 docstring val = split(s, key, ' ');
888                 posts[key] = val;
889         }
890         CiteItem ci;
891         ci.textBefore = qstring_to_ucs4(textBeforeED->text());
892         ci.textAfter = qstring_to_ucs4(textAfterED->text());
893         ci.forceUpperCase = forceuppercaseCB->isChecked();
894         ci.Starred = starredCB->isChecked();
895         ci.context = CiteItem::Dialog;
896         ci.max_size = max_size;
897         ci.isQualified = qualified;
898         ci.pretexts = pres;
899         ci.posttexts = posts;
900         BiblioInfo::CiteStringMap ret = bi.getCiteStrings(keys, styles, documentBuffer(), ci);
901         return ret;
902 }
903
904
905 void GuiCitation::setCitedKeys()
906 {
907         cited_keys_ = selectedKeys();
908         updateStyles();
909 }
910
911
912 bool GuiCitation::initialiseParams(string const & sdata)
913 {
914         InsetCommand::string2params(sdata, params_);
915         citeCmds_ = documentBuffer().params().citeCommands();
916         citeStyles_ = documentBuffer().params().citeStyles();
917         init();
918         return true;
919 }
920
921
922 void GuiCitation::clearParams()
923 {
924         params_.clear();
925 }
926
927
928 void GuiCitation::filterByEntryType(BiblioInfo const & bi,
929         vector<docstring> & keyVector, docstring entry_type)
930 {
931         if (entry_type.empty())
932                 return;
933
934         vector<docstring>::iterator it = keyVector.begin();
935         vector<docstring>::iterator end = keyVector.end();
936
937         vector<docstring> result;
938         for (; it != end; ++it) {
939                 docstring const key = *it;
940                 BiblioInfo::const_iterator cit = bi.find(key);
941                 if (cit == bi.end())
942                         continue;
943                 if (cit->second.entryType() == entry_type)
944                         result.push_back(key);
945         }
946         keyVector = result;
947 }
948
949
950 // Escape special chars.
951 // All characters are literals except: '.|*?+(){}[]^$\'
952 // These characters are literals when preceded by a "\", which is done here
953 // @todo: This function should be moved to support, and then the test in tests
954 //        should be moved there as well.
955 static docstring escape_special_chars(docstring const & expr)
956 {
957         // Search for all chars '.|*?+(){}[^$]\'
958         // Note that '[', ']', and '\' must be escaped.
959         static const lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
960
961         // $& is an ECMAScript format expression that expands to all
962         // of the current match
963 #ifdef LYX_USE_STD_REGEX
964         // To prefix a matched expression with a single literal backslash, we
965         // need to escape it for the C++ compiler and use:
966         // FIXME: UNICODE
967         return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\$&")));
968 #else
969         // A backslash in the format string starts an escape sequence in boost.
970         // Thus, to prefix a matched expression with a single literal backslash,
971         // we need to give two backslashes to the regex engine, and escape both
972         // for the C++ compiler and use:
973         // FIXME: UNICODE
974         return from_utf8(lyx::regex_replace(to_utf8(expr), reg, string("\\\\$&")));
975 #endif
976 }
977
978
979 vector<docstring> GuiCitation::searchKeys(BiblioInfo const & bi,
980         vector<docstring> const & keys_to_search, bool only_keys,
981         docstring const & search_expression, docstring field,
982         bool case_sensitive, bool regex)
983 {
984         vector<docstring> foundKeys;
985
986         docstring expr = trim(search_expression);
987         if (expr.empty())
988                 return foundKeys;
989
990         if (!regex)
991                 // We must escape special chars in the search_expr so that
992                 // it is treated as a simple string by lyx::regex.
993                 expr = escape_special_chars(expr);
994
995         lyx::regex reg_exp;
996         try {
997                 reg_exp.assign(to_utf8(expr), case_sensitive ?
998                         lyx::regex_constants::ECMAScript : lyx::regex_constants::icase);
999         } catch (lyx::regex_error const & e) {
1000                 // lyx::regex throws an exception if the regular expression is not
1001                 // valid.
1002                 LYXERR(Debug::GUI, e.what());
1003                 return vector<docstring>();
1004         }
1005
1006         vector<docstring>::const_iterator it = keys_to_search.begin();
1007         vector<docstring>::const_iterator end = keys_to_search.end();
1008         for (; it != end; ++it ) {
1009                 BiblioInfo::const_iterator info = bi.find(*it);
1010                 if (info == bi.end())
1011                         continue;
1012
1013                 BibTeXInfo const & kvm = info->second;
1014                 string sdata;
1015                 if (only_keys)
1016                         sdata = to_utf8(*it);
1017                 else if (field.empty())
1018                         sdata = to_utf8(*it) + ' ' + to_utf8(kvm.allData());
1019                 else
1020                         sdata = to_utf8(kvm[field]);
1021
1022                 if (sdata.empty())
1023                         continue;
1024
1025                 try {
1026                         if (lyx::regex_search(sdata, reg_exp))
1027                                 foundKeys.push_back(*it);
1028                 }
1029                 catch (lyx::regex_error const & e) {
1030                         LYXERR(Debug::GUI, e.what());
1031                         return vector<docstring>();
1032                 }
1033         }
1034         return foundKeys;
1035 }
1036
1037
1038 void GuiCitation::dispatchParams()
1039 {
1040         std::string const lfun = InsetCommand::params2string(params_);
1041         dispatch(FuncRequest(getLfun(), lfun));
1042 }
1043
1044
1045 BiblioInfo const & GuiCitation::bibInfo() const
1046 {
1047         Buffer const & buf = documentBuffer();
1048         buf.reloadBibInfoCache();
1049         return buf.masterBibInfo();
1050 }
1051
1052
1053 void GuiCitation::saveSession(QSettings & settings) const
1054 {
1055         Dialog::saveSession(settings);
1056         settings.setValue(
1057                 sessionKey() + "/regex", regexp_->isChecked());
1058         settings.setValue(
1059                 sessionKey() + "/casesensitive", casesense_->isChecked());
1060         settings.setValue(
1061                 sessionKey() + "/autofind", instant_->isChecked());
1062         settings.setValue(
1063                 sessionKey() + "/citestyle", style_);
1064         settings.setValue(
1065                 sessionKey() + "/literal", InsetCitation::last_literal);
1066 }
1067
1068
1069 void GuiCitation::restoreSession()
1070 {
1071         Dialog::restoreSession();
1072         QSettings settings;
1073         regexp_->setChecked(settings.value(sessionKey() + "/regex").toBool());
1074         casesense_->setChecked(settings.value(sessionKey() + "/casesensitive").toBool());
1075         instant_->setChecked(settings.value(sessionKey() + "/autofind", true).toBool());
1076         style_ = settings.value(sessionKey() + "/citestyle").toString();
1077         InsetCitation::last_literal = 
1078                 settings.value(sessionKey() + "/literal", false).toBool();
1079         updateFilterHint();
1080 }
1081
1082
1083 Dialog * createGuiCitation(GuiView & lv) { return new GuiCitation(lv); }
1084
1085
1086 } // namespace frontend
1087 } // namespace lyx
1088
1089 #include "moc_GuiCitation.cpp"
1090