]> git.lyx.org Git - lyx.git/blobdiff - src/frontends/qt4/GuiDocument.cpp
GuiDocument.cpp: add missing validation code
[lyx.git] / src / frontends / qt4 / GuiDocument.cpp
index e74c1934c4f78c0baa5e58b5b53291d68ad3b66b..691bb2c9249da2c967eef959adb60ef7f4a19a3a 100644 (file)
 #include "Buffer.h"
 #include "BufferParams.h"
 #include "BufferView.h"
+#include "CiteEnginesList.h"
 #include "Color.h"
 #include "ColorCache.h"
+#include "Converter.h"
+#include "Cursor.h"
 #include "Encoding.h"
 #include "FloatPlacement.h"
 #include "Format.h"
@@ -50,6 +53,8 @@
 #include "qt_helpers.h"
 #include "Spacing.h"
 #include "TextClass.h"
+#include "Undo.h"
+#include "VSpace.h"
 
 #include "insets/InsetListingsParams.h"
 
@@ -69,6 +74,7 @@
 #include <QCloseEvent>
 #include <QFontDatabase>
 #include <QScrollBar>
+#include <QTextBoundaryFinder>
 #include <QTextCursor>
 
 #include <sstream>
@@ -149,6 +155,7 @@ RGBColor set_fontcolor;
 bool is_fontcolor;
 RGBColor set_notefontcolor;
 RGBColor set_boxbgcolor;
+bool forced_fontspec_activation;
 
 namespace {
 // used when sorting the textclass list.
@@ -244,18 +251,19 @@ class ModuleSelectionManager : public GuiSelectionManager
 {
 public:
        ///
-       ModuleSelectionManager(
-               QTreeView * availableLV,
-               QListView * selectedLV,
-               QPushButton * addPB,
-               QPushButton * delPB,
-               QPushButton * upPB,
-               QPushButton * downPB,
-               GuiIdListModel * availableModel,
-               GuiIdListModel * selectedModel,
-               GuiDocument const * container)
-       : GuiSelectionManager(availableLV, selectedLV, addPB, delPB,
-                               upPB, downPB, availableModel, selectedModel), container_(container)
+       ModuleSelectionManager(QObject * parent,
+                              QTreeView * availableLV,
+                              QListView * selectedLV,
+                              QPushButton * addPB,
+                              QPushButton * delPB,
+                              QPushButton * upPB,
+                              QPushButton * downPB,
+                              GuiIdListModel * availableModel,
+                              GuiIdListModel * selectedModel,
+                              GuiDocument const * container)
+               : GuiSelectionManager(parent, availableLV, selectedLV, addPB, delPB,
+                                     upPB, downPB, availableModel, selectedModel),
+                 container_(container)
                {}
        ///
        void updateProvidedModules(LayoutModuleList const & pm)
@@ -444,11 +452,15 @@ void ModuleSelectionManager::updateDelPB()
 //
 /////////////////////////////////////////////////////////////////////
 
-PreambleModule::PreambleModule() : current_id_(0)
+PreambleModule::PreambleModule(QWidget * parent)
+       : UiWidget<Ui::PreambleUi>(parent), current_id_(0)
 {
        // This is not a memory leak. The object will be destroyed
        // with this.
-       (void) new LaTeXHighlighter(preambleTE->document());
+       // @ is letter in the LyX user preamble
+       (void) new LaTeXHighlighter(preambleTE->document(), true);
+       preambleTE->setFont(guiApp->typewriterSystemFont());
+       preambleTE->setWordWrapMode(QTextOption::NoWrap);
        setFocusProxy(preambleTE);
        connect(preambleTE, SIGNAL(textChanged()), this, SIGNAL(changed()));
 }
@@ -486,7 +498,7 @@ void PreambleModule::update(BufferParams const & params, BufferId id)
 
 void PreambleModule::apply(BufferParams & params)
 {
-       params.preamble = fromqstr(preambleTE->document()->toPlainText());
+       params.preamble = qstring_to_ucs4(preambleTE->document()->toPlainText());
 }
 
 
@@ -507,7 +519,8 @@ void PreambleModule::closeEvent(QCloseEvent * e)
 /////////////////////////////////////////////////////////////////////
 
 
-LocalLayout::LocalLayout() : current_id_(0), validated_(false)
+LocalLayout::LocalLayout(QWidget * parent)
+       : UiWidget<Ui::LocalLayoutUi>(parent), current_id_(0), validated_(false)
 {
        connect(locallayoutTE, SIGNAL(textChanged()), this, SLOT(textChanged()));
        connect(validatePB, SIGNAL(clicked()), this, SLOT(validatePressed()));
@@ -517,7 +530,7 @@ LocalLayout::LocalLayout() : current_id_(0), validated_(false)
 
 void LocalLayout::update(BufferParams const & params, BufferId id)
 {
-       QString layout = toqstr(params.local_layout);
+       QString layout = toqstr(params.getLocalLayout(false));
        // Nothing to do if the params and preamble are unchanged.
        if (id == current_id_
                && layout == locallayoutTE->document()->toPlainText())
@@ -532,8 +545,18 @@ void LocalLayout::update(BufferParams const & params, BufferId id)
 
 void LocalLayout::apply(BufferParams & params)
 {
-       string const layout = fromqstr(locallayoutTE->document()->toPlainText());
-       params.local_layout = layout;
+       docstring const layout =
+               qstring_to_ucs4(locallayoutTE->document()->toPlainText());
+       params.setLocalLayout(layout, false);
+}
+
+
+void LocalLayout::hideConvert()
+{
+       convertPB->setEnabled(false);
+       convertLB->setText("");
+       convertPB->hide();
+       convertLB->hide();
 }
 
 
@@ -548,15 +571,14 @@ void LocalLayout::textChanged()
                validated_ = true;
                validatePB->setEnabled(false);
                validLB->setText("");
-               convertPB->hide();
-               convertLB->hide();
+               hideConvert();
                changed();
        } else if (!validatePB->isEnabled()) {
                // if that's already enabled, we shouldn't need to do anything.
                validated_ = false;
                validLB->setText(message);
                validatePB->setEnabled(true);
-               convertPB->setEnabled(false);
+               hideConvert();
                changed();
        }
 }
@@ -566,44 +588,52 @@ void LocalLayout::convert() {
        string const layout =
                fromqstr(locallayoutTE->document()->toPlainText().trimmed());
        string const newlayout = TextClass::convert(layout);
-       LYXERR0(newlayout);
-       if (newlayout.empty()) {
-               Alert::error(_("Conversion Failed!"),
-                     _("Failed to convert local layout to current format."));
-       } else {
+       if (!newlayout.empty())
                locallayoutTE->setPlainText(toqstr(newlayout));
-       }
        validate();
 }
 
 
 void LocalLayout::convertPressed() {
        convert();
+       hideConvert();
        changed();
 }
 
 
 void LocalLayout::validate() {
-       static const QString valid = qt_("Layout is valid!");
-       static const QString vtext =
-               toqstr("<p style=\"font-weight: bold; \">")
-                 + valid + toqstr("</p>");
-       static const QString invalid = qt_("Layout is invalid!");
-       static const QString ivtext =
-               toqstr("<p style=\"color: #c00000; font-weight: bold; \">")
-                 + invalid + toqstr("</p>");
-
+       // Bold text
+       static const QString vpar("<p style=\"font-weight: bold;\">%1</p>");
+       // Flashy red bold text
+       static const QString ivpar("<p style=\"color: #c00000; font-weight: bold; \">"
+                                  "%1</p>");
        string const layout =
                fromqstr(locallayoutTE->document()->toPlainText().trimmed());
        if (!layout.empty()) {
                TextClass::ReturnValues const ret = TextClass::validate(layout);
                validated_ = (ret == TextClass::OK) || (ret == TextClass::OK_OLDFORMAT);
                validatePB->setEnabled(false);
-               validLB->setText(validated_ ? vtext : ivtext);
+               validLB->setText(validated_ ? vpar.arg(qt_("Layout is valid!"))
+                                           : ivpar.arg(qt_("Layout is invalid!")));
                if (ret == TextClass::OK_OLDFORMAT) {
                        convertPB->show();
-                       convertPB->setEnabled(true);
-                       convertLB->setText(qt_("Convert to current format"));
+                       // Testing conversion to LYXFILE_LAYOUT_FORMAT at this point
+                       // already.
+                       if (TextClass::convert(layout).empty()) {
+                               // Conversion failed. If LAYOUT_FORMAT > LYXFILE_LAYOUT_FORMAT,
+                               // then maybe the layout is still valid, but its format is more
+                               // recent than LYXFILE_LAYOUT_FORMAT. However, if LAYOUT_FORMAT
+                               // == LYXFILE_LAYOUT_FORMAT then something is definitely wrong.
+                               convertPB->setEnabled(false);
+                               const QString text = (LAYOUT_FORMAT == LYXFILE_LAYOUT_FORMAT)
+                                       ? ivpar.arg(qt_("Conversion to current format impossible!"))
+                                       : vpar.arg(qt_("Conversion to current stable format "
+                                                      "impossible."));
+                               convertLB->setText(text);
+                       } else {
+                               convertPB->setEnabled(true);
+                               convertLB->setText(qt_("Convert to current format"));
+                       }
                        convertLB->show();
                } else {
                        convertPB->hide();
@@ -627,7 +657,8 @@ void LocalLayout::validatePressed() {
 
 
 GuiDocument::GuiDocument(GuiView & lv)
-       : GuiDialog(lv, "document", qt_("Document Settings"))
+       : GuiDialog(lv, "document", qt_("Document Settings")),
+         biblioChanged_(false), nonModuleChanged_(false)
 {
        setupUi(this);
 
@@ -648,7 +679,7 @@ GuiDocument::GuiDocument(GuiView & lv)
 
 
        // text layout
-       textLayoutModule = new UiWidget<Ui::TextLayoutUi>;
+       textLayoutModule = new UiWidget<Ui::TextLayoutUi>(this);
        connect(textLayoutModule->lspacingCO, SIGNAL(activated(int)),
                this, SLOT(change_adaptor()));
        connect(textLayoutModule->lspacingCO, SIGNAL(activated(int)),
@@ -694,11 +725,32 @@ GuiDocument::GuiDocument(GuiView & lv)
        connect(textLayoutModule->justCB, SIGNAL(clicked()),
                this, SLOT(change_adaptor()));
 
+       connect(textLayoutModule->MathIndentCB, SIGNAL(toggled(bool)),
+               this, SLOT(change_adaptor()));
+       connect(textLayoutModule->MathIndentCB, SIGNAL(toggled(bool)),
+               this, SLOT(allowMathIndent()));
+       connect(textLayoutModule->MathIndentCO, SIGNAL(activated(int)),
+               this, SLOT(change_adaptor()));
+       connect(textLayoutModule->MathIndentCO, SIGNAL(activated(int)),
+               this, SLOT(setMathIndent(int)));
+       connect(textLayoutModule->MathIndentLE, SIGNAL(textChanged(const QString &)),
+               this, SLOT(change_adaptor()));
+       connect(textLayoutModule->MathIndentLengthCO, SIGNAL(activated(int)),
+               this, SLOT(change_adaptor()));
+
+       
+       textLayoutModule->MathIndentCO->addItem(qt_("Default"));
+       textLayoutModule->MathIndentCO->addItem(qt_("Custom"));
+       textLayoutModule->MathIndentLE->setValidator(new LengthValidator(
+               textLayoutModule->MathIndentLE));
+       // initialize the length validator
+       bc().addCheckedLineEdit(textLayoutModule->MathIndentLE);
+       
        textLayoutModule->lspacingLE->setValidator(new QDoubleValidator(
                textLayoutModule->lspacingLE));
-       textLayoutModule->indentLE->setValidator(unsignedLengthValidator(
+       textLayoutModule->indentLE->setValidator(new LengthValidator(
                textLayoutModule->indentLE));
-       textLayoutModule->skipLE->setValidator(unsignedGlueLengthValidator(
+       textLayoutModule->skipLE->setValidator(new LengthValidator(
                textLayoutModule->skipLE));
 
        textLayoutModule->indentCO->addItem(qt_("Default"));
@@ -721,7 +773,7 @@ GuiDocument::GuiDocument(GuiView & lv)
 
 
        // master/child handling
-       masterChildModule = new UiWidget<Ui::MasterChildUi>;
+       masterChildModule = new UiWidget<Ui::MasterChildUi>(this);
 
        connect(masterChildModule->childrenTW, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
                this, SLOT(includeonlyClicked(QTreeWidgetItem *, int)));
@@ -742,8 +794,8 @@ GuiDocument::GuiDocument(GuiView & lv)
        masterChildModule->childrenTW->resizeColumnToContents(2);
 
 
-       // output
-       outputModule = new UiWidget<Ui::OutputUi>;
+       // Formats
+       outputModule = new UiWidget<Ui::OutputUi>(this);
 
        connect(outputModule->defaultFormatCO, SIGNAL(activated(int)),
                this, SLOT(change_adaptor()));
@@ -768,8 +820,11 @@ GuiDocument::GuiDocument(GuiView & lv)
        outputModule->synccustomCB->setValidator(new NoNewLineValidator(
                outputModule->synccustomCB));
 
+       connect(outputModule->saveTransientPropertiesCB, SIGNAL(clicked()),
+               this, SLOT(change_adaptor()));
+
        // fonts
-       fontModule = new UiWidget<Ui::FontUi>;
+       fontModule = new FontModule(this);
        connect(fontModule->osFontsCB, SIGNAL(clicked()),
                this, SLOT(change_adaptor()));
        connect(fontModule->osFontsCB, SIGNAL(toggled(bool)),
@@ -802,6 +857,10 @@ GuiDocument::GuiDocument(GuiView & lv)
                this, SLOT(change_adaptor()));
        connect(fontModule->cjkFontLE, SIGNAL(textChanged(const QString &)),
                this, SLOT(change_adaptor()));
+       connect(fontModule->microtypeCB, SIGNAL(clicked()),
+               this, SLOT(change_adaptor()));
+       connect(fontModule->dashesCB, SIGNAL(clicked()),
+               this, SLOT(change_adaptor()));
        connect(fontModule->scaleSansSB, SIGNAL(valueChanged(int)),
                this, SLOT(change_adaptor()));
        connect(fontModule->scaleTypewriterSB, SIGNAL(valueChanged(int)),
@@ -842,7 +901,7 @@ GuiDocument::GuiDocument(GuiView & lv)
 
 
        // page layout
-       pageLayoutModule = new UiWidget<Ui::PageLayoutUi>;
+       pageLayoutModule = new UiWidget<Ui::PageLayoutUi>(this);
        connect(pageLayoutModule->papersizeCO, SIGNAL(activated(int)),
                this, SLOT(papersizeChanged(int)));
        connect(pageLayoutModule->papersizeCO, SIGNAL(activated(int)),
@@ -922,7 +981,7 @@ GuiDocument::GuiDocument(GuiView & lv)
 
 
        // margins
-       marginsModule = new UiWidget<Ui::MarginsUi>;
+       marginsModule = new UiWidget<Ui::MarginsUi>(this);
        connect(marginsModule->marginCB, SIGNAL(toggled(bool)),
                this, SLOT(setCustomMargins(bool)));
        connect(marginsModule->marginCB, SIGNAL(clicked()),
@@ -959,21 +1018,21 @@ GuiDocument::GuiDocument(GuiView & lv)
                this, SLOT(change_adaptor()));
        connect(marginsModule->columnsepUnit, SIGNAL(activated(int)),
                this, SLOT(change_adaptor()));
-       marginsModule->topLE->setValidator(unsignedLengthValidator(
+       marginsModule->topLE->setValidator(new LengthValidator(
                marginsModule->topLE));
-       marginsModule->bottomLE->setValidator(unsignedLengthValidator(
+       marginsModule->bottomLE->setValidator(new LengthValidator(
                marginsModule->bottomLE));
-       marginsModule->innerLE->setValidator(unsignedLengthValidator(
+       marginsModule->innerLE->setValidator(new LengthValidator(
                marginsModule->innerLE));
-       marginsModule->outerLE->setValidator(unsignedLengthValidator(
+       marginsModule->outerLE->setValidator(new LengthValidator(
                marginsModule->outerLE));
-       marginsModule->headsepLE->setValidator(unsignedLengthValidator(
+       marginsModule->headsepLE->setValidator(new LengthValidator(
                marginsModule->headsepLE));
-       marginsModule->headheightLE->setValidator(unsignedLengthValidator(
+       marginsModule->headheightLE->setValidator(new LengthValidator(
                marginsModule->headheightLE));
-       marginsModule->footskipLE->setValidator(unsignedLengthValidator(
+       marginsModule->footskipLE->setValidator(new LengthValidator(
                marginsModule->footskipLE));
-       marginsModule->columnsepLE->setValidator(unsignedLengthValidator(
+       marginsModule->columnsepLE->setValidator(new LengthValidator(
                marginsModule->columnsepLE));
 
        bc().addCheckedLineEdit(marginsModule->topLE,
@@ -995,7 +1054,7 @@ GuiDocument::GuiDocument(GuiView & lv)
 
 
        // language & quote
-       langModule = new UiWidget<Ui::LanguageUi>;
+       langModule = new UiWidget<Ui::LanguageUi>(this);
        connect(langModule->languageCO, SIGNAL(activated(int)),
                this, SLOT(change_adaptor()));
        connect(langModule->languageCO, SIGNAL(activated(int)),
@@ -1014,6 +1073,8 @@ GuiDocument::GuiDocument(GuiView & lv)
                this, SLOT(change_adaptor()));
        connect(langModule->languagePackageCO, SIGNAL(currentIndexChanged(int)),
                this, SLOT(languagePackageChanged(int)));
+       connect(langModule->dynamicQuotesCB, SIGNAL(clicked()),
+               this, SLOT(change_adaptor()));
 
        langModule->languagePackageLE->setValidator(new NoNewLineValidator(
                langModule->languagePackageLE));
@@ -1035,19 +1096,6 @@ GuiDocument::GuiDocument(GuiView & lv)
        encodinglist.sort();
        langModule->encodingCO->addItems(encodinglist);
 
-       langModule->quoteStyleCO->addItem(
-               qt_("``text''"),InsetQuotes::EnglishQuotes);
-       langModule->quoteStyleCO->addItem(
-               qt_("''text''"), InsetQuotes::SwedishQuotes);
-       langModule->quoteStyleCO->addItem
-               (qt_(",,text``"), InsetQuotes::GermanQuotes);
-       langModule->quoteStyleCO->addItem(
-               qt_(",,text''"), InsetQuotes::PolishQuotes);
-       langModule->quoteStyleCO->addItem(
-               qt_("<<text>>"), InsetQuotes::FrenchQuotes);
-       langModule->quoteStyleCO->addItem(
-               qt_(">>text<<"), InsetQuotes::DanishQuotes);
-
        langModule->languagePackageCO->addItem(
                qt_("Default"), toqstr("default"));
        langModule->languagePackageCO->addItem(
@@ -1061,7 +1109,7 @@ GuiDocument::GuiDocument(GuiView & lv)
 
 
        // color
-       colorModule = new UiWidget<Ui::ColorUi>;
+       colorModule = new UiWidget<Ui::ColorUi>(this);
        connect(colorModule->fontColorPB, SIGNAL(clicked()),
                this, SLOT(changeFontColor()));
        connect(colorModule->delFontColorTB, SIGNAL(clicked()),
@@ -1081,7 +1129,7 @@ GuiDocument::GuiDocument(GuiView & lv)
 
 
        // numbering
-       numberingModule = new UiWidget<Ui::NumberingUi>;
+       numberingModule = new UiWidget<Ui::NumberingUi>(this);
        connect(numberingModule->depthSL, SIGNAL(valueChanged(int)),
                this, SLOT(change_adaptor()));
        connect(numberingModule->tocSL, SIGNAL(valueChanged(int)),
@@ -1097,40 +1145,58 @@ GuiDocument::GuiDocument(GuiView & lv)
        setSectionResizeMode(numberingModule->tocTW->header(), QHeaderView::ResizeToContents);
 
        // biblio
-       biblioModule = new UiWidget<Ui::BiblioUi>;
-       connect(biblioModule->citeDefaultRB, SIGNAL(toggled(bool)),
-               this, SLOT(setNumerical(bool)));
-       connect(biblioModule->citeJurabibRB, SIGNAL(toggled(bool)),
-               this, SLOT(setAuthorYear(bool)));
-       connect(biblioModule->citeNatbibRB, SIGNAL(toggled(bool)),
-               biblioModule->citationStyleL, SLOT(setEnabled(bool)));
-       connect(biblioModule->citeNatbibRB, SIGNAL(toggled(bool)),
-               biblioModule->citeStyleCO, SLOT(setEnabled(bool)));
-       connect(biblioModule->citeDefaultRB, SIGNAL(clicked()),
-               this, SLOT(biblioChanged()));
-       connect(biblioModule->citeNatbibRB, SIGNAL(clicked()),
-               this, SLOT(biblioChanged()));
+       biblioModule = new UiWidget<Ui::BiblioUi>(this);
+       connect(biblioModule->citeEngineCO, SIGNAL(activated(int)),
+               this, SLOT(citeEngineChanged(int)));
        connect(biblioModule->citeStyleCO, SIGNAL(activated(int)),
-               this, SLOT(biblioChanged()));
-       connect(biblioModule->citeJurabibRB, SIGNAL(clicked()),
-               this, SLOT(biblioChanged()));
+               this, SLOT(citeStyleChanged()));
        connect(biblioModule->bibtopicCB, SIGNAL(clicked()),
                this, SLOT(biblioChanged()));
+       connect(biblioModule->bibunitsCO, SIGNAL(activated(int)),
+               this, SLOT(biblioChanged()));
        connect(biblioModule->bibtexCO, SIGNAL(activated(int)),
                this, SLOT(bibtexChanged(int)));
        connect(biblioModule->bibtexOptionsLE, SIGNAL(textChanged(QString)),
                this, SLOT(biblioChanged()));
-       connect(biblioModule->bibtexStyleLE, SIGNAL(textChanged(QString)),
+       connect(biblioModule->citePackageOptionsLE, SIGNAL(textChanged(QString)),
+               this, SLOT(biblioChanged()));
+       connect(biblioModule->defaultBiblioCO, SIGNAL(activated(int)),
                this, SLOT(biblioChanged()));
+       connect(biblioModule->defaultBiblioCO, SIGNAL(editTextChanged(QString)),
+               this, SLOT(biblioChanged()));
+       connect(biblioModule->defaultBiblioCO, SIGNAL(editTextChanged(QString)),
+               this, SLOT(updateResetDefaultBiblio()));
+       connect(biblioModule->biblatexBbxCO, SIGNAL(activated(int)),
+               this, SLOT(biblioChanged()));
+       connect(biblioModule->biblatexBbxCO, SIGNAL(editTextChanged(QString)),
+               this, SLOT(updateResetDefaultBiblio()));
+       connect(biblioModule->biblatexCbxCO, SIGNAL(activated(int)),
+               this, SLOT(biblioChanged()));
+       connect(biblioModule->biblatexCbxCO, SIGNAL(editTextChanged(QString)),
+               this, SLOT(updateResetDefaultBiblio()));
+       connect(biblioModule->rescanBibliosPB, SIGNAL(clicked()),
+               this, SLOT(rescanBibFiles()));
+       connect(biblioModule->resetDefaultBiblioPB, SIGNAL(clicked()),
+               this, SLOT(resetDefaultBibfile()));
+       connect(biblioModule->resetCbxPB, SIGNAL(clicked()),
+               this, SLOT(resetDefaultCbxBibfile()));
+       connect(biblioModule->resetBbxPB, SIGNAL(clicked()),
+               this, SLOT(resetDefaultBbxBibfile()));
+       connect(biblioModule->matchBbxPB, SIGNAL(clicked()),
+               this, SLOT(matchBiblatexStyles()));
+
+       biblioModule->citeEngineCO->clear();
+       for (LyXCiteEngine const & cet : theCiteEnginesList) {
+               biblioModule->citeEngineCO->addItem(qt_(cet.getName()), toqstr(cet.getID()));
+               int const i = biblioModule->citeEngineCO->findData(toqstr(cet.getID()));
+               biblioModule->citeEngineCO->setItemData(i, qt_(cet.getDescription()),
+                                                       Qt::ToolTipRole);
+       }
 
        biblioModule->bibtexOptionsLE->setValidator(new NoNewLineValidator(
                biblioModule->bibtexOptionsLE));
-       biblioModule->bibtexStyleLE->setValidator(new NoNewLineValidator(
-               biblioModule->bibtexStyleLE));
-
-       biblioModule->citeStyleCO->addItem(qt_("Author-year"));
-       biblioModule->citeStyleCO->addItem(qt_("Numerical"));
-       biblioModule->citeStyleCO->setCurrentIndex(0);
+       biblioModule->defaultBiblioCO->lineEdit()->setValidator(new NoNewLineValidator(
+               biblioModule->defaultBiblioCO->lineEdit()));
 
        // NOTE: we do not provide "custom" here for security reasons!
        biblioModule->bibtexCO->clear();
@@ -1149,12 +1215,12 @@ GuiDocument::GuiDocument(GuiView & lv)
 
 
        // maths
-       mathsModule = new UiWidget<Ui::MathsUi>;
+       mathsModule = new UiWidget<Ui::MathsUi>(this);
        QStringList headers;
        headers << qt_("Package") << qt_("Load automatically")
                << qt_("Load always") << qt_("Do not load");
        mathsModule->packagesTW->setHorizontalHeaderLabels(headers);
-       setSectionResizeMode(mathsModule->packagesTW->horizontalHeader(), QHeaderView::Stretch);        
+       setSectionResizeMode(mathsModule->packagesTW->horizontalHeader(), QHeaderView::Stretch);
        map<string, string> const & packages = BufferParams::auto_packages();
        mathsModule->packagesTW->setRowCount(packages.size());
        int i = 0;
@@ -1208,10 +1274,16 @@ GuiDocument::GuiDocument(GuiView & lv)
                this, SLOT(allPackagesAlways()));
        connect(mathsModule->allPackagesNotPB, SIGNAL(clicked()),
                this, SLOT(allPackagesNot()));
-
+       connect(mathsModule->allPackagesAutoPB, SIGNAL(clicked()),
+               this, SLOT(change_adaptor()));
+       connect(mathsModule->allPackagesAlwaysPB, SIGNAL(clicked()),
+               this, SLOT(change_adaptor()));
+       connect(mathsModule->allPackagesNotPB, SIGNAL(clicked()),
+               this, SLOT(change_adaptor()));
+       
 
        // latex class
-       latexModule = new UiWidget<Ui::LaTeXUi>;
+       latexModule = new UiWidget<Ui::LaTeXUi>(this);
        connect(latexModule->optionsLE, SIGNAL(textChanged(QString)),
                this, SLOT(change_adaptor()));
        connect(latexModule->defaultOptionsCB, SIGNAL(clicked()),
@@ -1219,7 +1291,7 @@ GuiDocument::GuiDocument(GuiView & lv)
        connect(latexModule->psdriverCO, SIGNAL(activated(int)),
                this, SLOT(change_adaptor()));
        connect(latexModule->classCO, SIGNAL(activated(int)),
-               this, SLOT(classChanged()));
+               this, SLOT(classChanged_adaptor()));
        connect(latexModule->classCO, SIGNAL(activated(int)),
                this, SLOT(change_adaptor()));
        connect(latexModule->layoutPB, SIGNAL(clicked()),
@@ -1262,10 +1334,10 @@ GuiDocument::GuiDocument(GuiView & lv)
                QString tooltip = toqstr(bformat(_("%1$s [Class '%2$s']"), guiname, from_utf8(tc.latexname())));
                if (!available) {
                        docstring const output_type = (tc.outputType() == lyx::DOCBOOK) ? _("DocBook") : _("LaTeX");
-                       tooltip += '\n' + toqstr(wrap(bformat(_("Class not found by LyX. "
+                       tooltip += '\n' + toqstr(bformat(_("Class not found by LyX. "
                                                           "Please check if you have the matching %1$s class "
                                                           "and all required packages (%2$s) installed."),
-                                                        output_type, from_utf8(tc.prerequisites(", ")))));
+                                                        output_type, from_utf8(tc.prerequisites(", "))));
                }
                latexModule->classCO->addItemSort(toqstr(tc.name()),
                                                  toqstr(guiname),
@@ -1276,7 +1348,7 @@ GuiDocument::GuiDocument(GuiView & lv)
 
 
        // branches
-       branchesModule = new GuiBranches;
+       branchesModule = new GuiBranches(this);
        connect(branchesModule, SIGNAL(changed()),
                this, SLOT(change_adaptor()));
        connect(branchesModule, SIGNAL(renameBranches(docstring const &, docstring const &)),
@@ -1286,42 +1358,42 @@ GuiDocument::GuiDocument(GuiView & lv)
 
 
        // preamble
-       preambleModule = new PreambleModule;
+       preambleModule = new PreambleModule(this);
        connect(preambleModule, SIGNAL(changed()),
                this, SLOT(change_adaptor()));
 
-       localLayout = new LocalLayout;
+       localLayout = new LocalLayout(this);
        connect(localLayout, SIGNAL(changed()),
                this, SLOT(change_adaptor()));
 
 
        // bullets
-       bulletsModule = new BulletsModule;
+       bulletsModule = new BulletsModule(this);
        connect(bulletsModule, SIGNAL(changed()),
                this, SLOT(change_adaptor()));
 
 
        // Modules
-       modulesModule = new UiWidget<Ui::ModulesUi>;
+       modulesModule = new UiWidget<Ui::ModulesUi>(this);
        modulesModule->availableLV->header()->setVisible(false);
        setSectionResizeMode(modulesModule->availableLV->header(), QHeaderView::ResizeToContents);
        modulesModule->availableLV->header()->setStretchLastSection(false);
        selectionManager =
-               new ModuleSelectionManager(modulesModule->availableLV,
-                       modulesModule->selectedLV,
-                       modulesModule->addPB, modulesModule->deletePB,
-                       modulesModule->upPB, modulesModule->downPB,
-                       availableModel(), selectedModel(), this);
+               new ModuleSelectionManager(this, modulesModule->availableLV,
+                                          modulesModule->selectedLV,
+                                          modulesModule->addPB,
+                                          modulesModule->deletePB,
+                                          modulesModule->upPB,
+                                          modulesModule->downPB,
+                                          availableModel(), selectedModel(), this);
        connect(selectionManager, SIGNAL(updateHook()),
                this, SLOT(updateModuleInfo()));
-       connect(selectionManager, SIGNAL(updateHook()),
-               this, SLOT(change_adaptor()));
        connect(selectionManager, SIGNAL(selectionChanged()),
                this, SLOT(modulesChanged()));
 
 
        // PDF support
-       pdfSupportModule = new UiWidget<Ui::PDFSupportUi>;
+       pdfSupportModule = new UiWidget<Ui::PDFSupportUi>(this);
        connect(pdfSupportModule->use_hyperrefGB, SIGNAL(toggled(bool)),
                this, SLOT(change_adaptor()));
        connect(pdfSupportModule->titleLE, SIGNAL(textChanged(QString)),
@@ -1377,7 +1449,7 @@ GuiDocument::GuiDocument(GuiView & lv)
 
 
        // listings
-       listingsModule = new UiWidget<Ui::ListingsSettingsUi>;
+       listingsModule = new UiWidget<Ui::ListingsSettingsUi>(this);
        connect(listingsModule->listingsED, SIGNAL(textChanged()),
                this, SLOT(change_adaptor()));
        connect(listingsModule->bypassCB, SIGNAL(clicked()),
@@ -1410,7 +1482,7 @@ GuiDocument::GuiDocument(GuiView & lv)
        docPS->addPanel(listingsModule, N_("Listings[[inset]]"));
        docPS->addPanel(bulletsModule, N_("Bullets"));
        docPS->addPanel(branchesModule, N_("Branches"));
-       docPS->addPanel(outputModule, N_("Output"));
+       docPS->addPanel(outputModule, N_("Formats[[output]]"));
        docPS->addPanel(preambleModule, N_("LaTeX Preamble"));
        docPS->setCurrentPanel("Document Class");
 // FIXME: hack to work around resizing bug in Qt >= 4.2
@@ -1421,6 +1493,13 @@ GuiDocument::GuiDocument(GuiView & lv)
 }
 
 
+void GuiDocument::onBufferViewChanged()
+{
+       if (isVisibleView())
+               initialiseParams("");
+}
+
+
 void GuiDocument::saveDefaultClicked()
 {
        saveDocDefault();
@@ -1435,6 +1514,7 @@ void GuiDocument::useDefaultsClicked()
 
 void GuiDocument::change_adaptor()
 {
+       nonModuleChanged_ = true;
        changed();
 }
 
@@ -1455,31 +1535,22 @@ void GuiDocument::includeonlyClicked(QTreeWidgetItem * item, int)
                includeonlys_.push_back(child);
 
        updateIncludeonlys();
-       changed();
+       change_adaptor();
 }
 
 
 QString GuiDocument::validateListingsParameters()
 {
-       // use a cache here to avoid repeated validation
-       // of the same parameters
-       static string param_cache;
-       static QString msg_cache;
-
        if (listingsModule->bypassCB->isChecked())
                return QString();
-
        string params = fromqstr(listingsModule->listingsED->toPlainText());
-       if (params != param_cache) {
-               param_cache = params;
-               msg_cache = toqstr(InsetListingsParams(params).validate());
-       }
-       return msg_cache;
+       return toqstr(InsetListingsParams(params).validate());
 }
 
 
 void GuiDocument::setListingsMessage()
 {
+       // FIXME THREAD
        static bool isOK = true;
        QString msg = validateListingsParameters();
        if (msg.isEmpty()) {
@@ -1489,7 +1560,7 @@ void GuiDocument::setListingsMessage()
                // listingsTB->setTextColor("black");
                listingsModule->listingsTB->setPlainText(
                        qt_("Input listings parameters below. "
-                "Enter ? for a list of parameters."));
+                           "Enter ? for a list of parameters."));
        } else {
                isOK = false;
                // listingsTB->setTextColor("red");
@@ -1541,6 +1612,30 @@ void GuiDocument::enableSkip(bool skip)
                setSkip(textLayoutModule->skipCO->currentIndex());
 }
 
+void GuiDocument::allowMathIndent()
+{
+       // only disable when not checked, checked does not always allow enabling
+       if (!textLayoutModule->MathIndentCB->isChecked()) {
+               textLayoutModule->MathIndentLE->setEnabled(false);
+               textLayoutModule->MathIndentLengthCO->setEnabled(false);
+       }
+       if (textLayoutModule->MathIndentCB->isChecked()
+           && textLayoutModule->MathIndentCO->currentIndex() == 1) {
+               textLayoutModule->MathIndentLE->setEnabled(true);
+               textLayoutModule->MathIndentLengthCO->setEnabled(true);
+               
+       }
+       isValid();
+}
+
+void GuiDocument::setMathIndent(int item)
+{
+       bool const enable = (item == 1);
+       textLayoutModule->MathIndentLE->setEnabled(enable);
+       textLayoutModule->MathIndentLengthCO->setEnabled(enable);
+       isValid();
+}
+
 
 void GuiDocument::setMargins()
 {
@@ -1632,7 +1727,7 @@ void GuiDocument::changeBackgroundColor()
        // save color
        set_backgroundcolor = rgbFromHexName(fromqstr(newColor.name()));
        is_backgroundcolor = true;
-       changed();
+       change_adaptor();
 }
 
 
@@ -1645,7 +1740,7 @@ void GuiDocument::deleteBackgroundColor()
        // save default color (white)
        set_backgroundcolor = rgbFromHexName("#ffffff");
        is_backgroundcolor = false;
-       changed();
+       change_adaptor();
 }
 
 
@@ -1662,7 +1757,7 @@ void GuiDocument::changeFontColor()
        // save color
        set_fontcolor = rgbFromHexName(fromqstr(newColor.name()));
        is_fontcolor = true;
-       changed();
+       change_adaptor();
 }
 
 
@@ -1675,7 +1770,7 @@ void GuiDocument::deleteFontColor()
        // save default color (black)
        set_fontcolor = rgbFromHexName("#000000");
        is_fontcolor = false;
-       changed();
+       change_adaptor();
 }
 
 
@@ -1690,7 +1785,7 @@ void GuiDocument::changeNoteFontColor()
                colorButtonStyleSheet(newColor));
        // save color
        set_notefontcolor = rgbFromHexName(fromqstr(newColor.name()));
-       changed();
+       change_adaptor();
 }
 
 
@@ -1700,7 +1795,7 @@ void GuiDocument::deleteNoteFontColor()
        theApp()->getRgbColor(Color_greyedouttext, set_notefontcolor);
        colorModule->noteFontColorPB->setStyleSheet(
                colorButtonStyleSheet(rgb2qcolor(set_notefontcolor)));
-       changed();
+       change_adaptor();
 }
 
 
@@ -1715,7 +1810,7 @@ void GuiDocument::changeBoxBackgroundColor()
                colorButtonStyleSheet(newColor));
        // save color
        set_boxbgcolor = rgbFromHexName(fromqstr(newColor.name()));
-       changed();
+       change_adaptor();
 }
 
 
@@ -1725,33 +1820,85 @@ void GuiDocument::deleteBoxBackgroundColor()
        theApp()->getRgbColor(Color_shadedbg, set_boxbgcolor);
        colorModule->boxBackgroundPB->setStyleSheet(
                colorButtonStyleSheet(rgb2qcolor(set_boxbgcolor)));
-       changed();
+       change_adaptor();
+}
+
+
+void GuiDocument::updateQuoteStyles(bool const set)
+{
+       Language const * lang = lyx::languages.getLanguage(
+               fromqstr(langModule->languageCO->itemData(
+                       langModule->languageCO->currentIndex()).toString()));
+
+       InsetQuotesParams::QuoteStyle def = bp_.getQuoteStyle(lang->quoteStyle());
+
+       langModule->quoteStyleCO->clear();
+
+       bool has_default = false;
+       for (int i = 0; i < quoteparams.stylescount(); ++i) {
+               InsetQuotesParams::QuoteStyle qs = InsetQuotesParams::QuoteStyle(i);
+               if (qs == InsetQuotesParams::DynamicQuotes)
+                       continue;
+               bool const langdef = (qs == def);
+               if (langdef) {
+                       // add the default style on top
+                       langModule->quoteStyleCO->insertItem(0,
+                               toqstr(quoteparams.getGuiLabel(qs, langdef)), qs);
+                       has_default = true;
+               }
+               else
+                       langModule->quoteStyleCO->addItem(
+                               toqstr(quoteparams.getGuiLabel(qs, langdef)), qs);
+       }
+       if (set && has_default)
+               // (re)set to the default style
+               langModule->quoteStyleCO->setCurrentIndex(0);
 }
 
 
 void GuiDocument::languageChanged(int i)
 {
-       // some languages only work with polyglossia/XeTeX
+       // some languages only work with polyglossia
        Language const * lang = lyx::languages.getLanguage(
                fromqstr(langModule->languageCO->itemData(i).toString()));
        if (lang->babel().empty() && !lang->polyglossia().empty()) {
+                       // If we force to switch fontspec on, store
+                       // current state (#8717)
+                       if (fontModule->osFontsCB->isEnabled())
+                               forced_fontspec_activation =
+                                       !fontModule->osFontsCB->isChecked();
                        fontModule->osFontsCB->setChecked(true);
                        fontModule->osFontsCB->setEnabled(false);
        }
-       else
+       else {
                fontModule->osFontsCB->setEnabled(true);
+               // If we have forced to switch fontspec on,
+               // restore previous state (#8717)
+               if (forced_fontspec_activation)
+                       fontModule->osFontsCB->setChecked(false);
+               forced_fontspec_activation = false;
+       }
 
        // set appropriate quotation mark style
-       if (!lang->quoteStyle().empty()) {
-               langModule->quoteStyleCO->setCurrentIndex(
-                       bp_.getQuoteStyle(lang->quoteStyle()));
-       }
+       updateQuoteStyles(true);
 }
 
 
 void GuiDocument::osFontsChanged(bool nontexfonts)
 {
        bool const tex_fonts = !nontexfonts;
+       // store current fonts
+       QString const font_roman = fontModule->fontsRomanCO->itemData(
+                       fontModule->fontsRomanCO->currentIndex()).toString();
+       QString const font_sans = fontModule->fontsSansCO->itemData(
+                       fontModule->fontsSansCO->currentIndex()).toString();
+       QString const font_typewriter = fontModule->fontsTypewriterCO->itemData(
+                       fontModule->fontsTypewriterCO->currentIndex()).toString();
+       QString const font_math = fontModule->fontsMathCO->itemData(
+                       fontModule->fontsMathCO->currentIndex()).toString();
+       int const font_sf_scale = fontModule->scaleSansSB->value();
+       int const font_tt_scale = fontModule->scaleTypewriterSB->value();
+
        updateFontlist();
        // store default format
        QString const dformat = outputModule->defaultFormatCO->itemData(
@@ -1763,6 +1910,28 @@ void GuiDocument::osFontsChanged(bool nontexfonts)
        if (index == -1)
                index = 0;
        outputModule->defaultFormatCO->setCurrentIndex(index);
+
+       // try to restore fonts which were selected two toggles ago
+       index = fontModule->fontsRomanCO->findData(fontModule->font_roman);
+       if (index != -1)
+               fontModule->fontsRomanCO->setCurrentIndex(index);
+       index = fontModule->fontsSansCO->findData(fontModule->font_sans);
+       if (index != -1)
+               fontModule->fontsSansCO->setCurrentIndex(index);
+       index = fontModule->fontsTypewriterCO->findData(fontModule->font_typewriter);
+       if (index != -1)
+               fontModule->fontsTypewriterCO->setCurrentIndex(index);
+       index = fontModule->fontsMathCO->findData(fontModule->font_math);
+       if (index != -1)
+               fontModule->fontsMathCO->setCurrentIndex(index);
+       // save fonts for next next toggle
+       fontModule->font_roman = font_roman;
+       fontModule->font_sans = font_sans;
+       fontModule->font_typewriter = font_typewriter;
+       fontModule->font_math = font_math;
+       fontModule->font_sf_scale = font_sf_scale;
+       fontModule->font_tt_scale = font_tt_scale;
+
        langModule->encodingCO->setEnabled(tex_fonts &&
                !langModule->defaultencodingRB->isChecked());
        langModule->defaultencodingRB->setEnabled(tex_fonts);
@@ -1780,7 +1949,7 @@ void GuiDocument::osFontsChanged(bool nontexfonts)
        if (!tex_fonts)
                fontModule->fontencLE->setEnabled(false);
        else
-               fontencChanged(fontModule->fontencCO->currentIndex()); 
+               fontencChanged(fontModule->fontencCO->currentIndex());
 }
 
 
@@ -1833,6 +2002,7 @@ void GuiDocument::updateFontOptions()
                                fontModule->fontsRomanCO->currentIndex()).toString();
        fontModule->fontScCB->setEnabled(providesSC(font));
        fontModule->fontOsfCB->setEnabled(providesOSF(font));
+       fontModule->dashesCB->setEnabled(tex_fonts);
        updateMathFonts(font);
 }
 
@@ -1870,7 +2040,7 @@ bool GuiDocument::completeFontset() const
        return (fontModule->fontsSansCO->itemData(
                        fontModule->fontsSansCO->currentIndex()).toString() == "default"
                && fontModule->fontsSansCO->itemData(
-                       fontModule->fontsSansCO->currentIndex()).toString() == "default");
+                       fontModule->fontsTypewriterCO->currentIndex()).toString() == "default");
 }
 
 
@@ -1916,7 +2086,7 @@ void GuiDocument::updateFontlist()
        fontModule->fontsTypewriterCO->clear();
        fontModule->fontsMathCO->clear();
 
-       // With XeTeX, we have access to all system fonts, but not the LaTeX fonts
+       // With fontspec (XeTeX, LuaTeX), we have access to all system fonts, but not the LaTeX fonts
        if (fontModule->osFontsCB->isChecked()) {
                fontModule->fontsRomanCO->addItem(qt_("Default"), QString("default"));
                fontModule->fontsSansCO->addItem(qt_("Default"), QString("default"));
@@ -1946,14 +2116,14 @@ void GuiDocument::updateFontlist()
                fontModule->fontsRomanCO->addItem(rmi.key(), rmi.value());
                ++rmi;
        }
-       
+
        fontModule->fontsSansCO->addItem(qt_("Default"), QString("default"));
        QMap<QString, QString>::const_iterator sfi = sffonts_.constBegin();
        while (sfi != sffonts_.constEnd()) {
                fontModule->fontsSansCO->addItem(sfi.key(), sfi.value());
                ++sfi;
        }
-       
+
        fontModule->fontsTypewriterCO->addItem(qt_("Default"), QString("default"));
        QMap<QString, QString>::const_iterator tti = ttfonts_.constBegin();
        while (tti != ttfonts_.constEnd()) {
@@ -2081,9 +2251,9 @@ void GuiDocument::browseLayout()
 
        int const ret = Alert::prompt(_("Local layout file"),
                _("The layout file you have selected is a local layout\n"
-                 "file, not one in the system or user directory. Your\n"
-                 "document may not work with this layout if you do not\n"
-                 "keep the layout file in the document directory."),
+                 "file, not one in the system or user directory.\n"
+                 "Your document will not work with this layout if you\n"
+                 "move the layout file to a different directory."),
                  1, 1, _("&Set Layout"), _("&Cancel"));
        if (ret == 1)
                return;
@@ -2092,9 +2262,9 @@ void GuiDocument::browseLayout()
        LayoutFileList & bcl = LayoutFileList::get();
        string classname = layoutFile.onlyFileName();
        // this will update an existing layout if that layout has been loaded before.
-       LayoutFileIndex name = bcl.addLocalLayout(
+       LayoutFileIndex name = support::onlyFileName(bcl.addLocalLayout(
                classname.substr(0, classname.size() - 7),
-               layoutFile.onlyPath().absFileName());
+               layoutFile.onlyPath().absFileName()));
 
        if (name.empty()) {
                Alert::error(_("Error"),
@@ -2102,6 +2272,8 @@ void GuiDocument::browseLayout()
                return;
        }
 
+       const_cast<Buffer &>(buffer()).setLayoutPos(layoutFile.onlyPath().absFileName());
+
        // do not trigger classChanged if there is no change.
        if (latexModule->classCO->currentText() == toqstr(name))
                return;
@@ -2140,6 +2312,13 @@ void GuiDocument::browseMaster()
 }
 
 
+void GuiDocument::classChanged_adaptor()
+{
+       const_cast<Buffer &>(buffer()).setLayoutPos(string());
+       classChanged();
+}
+
+
 void GuiDocument::classChanged()
 {
        int idx = latexModule->classCO->currentIndex();
@@ -2147,30 +2326,13 @@ void GuiDocument::classChanged()
                return;
        string const classname = fromqstr(latexModule->classCO->getData(idx));
 
-       // check whether the selected modules have changed.
-       bool modules_changed = false;
-       unsigned int const srows = selectedModel()->rowCount();
-       if (srows != bp_.getModules().size())
-               modules_changed = true;
-       else {
-               list<string>::const_iterator mit = bp_.getModules().begin();
-               list<string>::const_iterator men = bp_.getModules().end();
-               for (unsigned int i = 0; i < srows && mit != men; ++i, ++mit)
-                       if (selectedModel()->getIDString(i) != *mit) {
-                               modules_changed = true;
-                               break;
-                       }
-       }
-
-       if (modules_changed || lyxrc.auto_reset_options) {
-               if (applyPB->isEnabled()) {
-                       int const ret = Alert::prompt(_("Unapplied changes"),
-                                       _("Some changes in the dialog were not yet applied.\n"
-                                       "If you do not apply now, they will be lost after this action."),
-                                       1, 1, _("&Apply"), _("&Dismiss"));
-                       if (ret == 0)
-                               applyView();
-               }
+       if (applyPB->isEnabled()) {
+               int const ret = Alert::prompt(_("Unapplied changes"),
+                               _("Some changes in the dialog were not yet applied.\n"
+                               "If you do not apply now, they will be lost after this action."),
+                               1, 1, _("&Apply"), _("&Dismiss"));
+               if (ret == 0)
+                       applyView();
        }
 
        // We load the TextClass as soon as it is selected. This is
@@ -2206,34 +2368,142 @@ void GuiDocument::languagePackageChanged(int i)
 void GuiDocument::biblioChanged()
 {
        biblioChanged_ = true;
-       changed();
+       change_adaptor();
 }
 
 
-void GuiDocument::bibtexChanged(int n)
+void GuiDocument::rescanBibFiles()
 {
-       biblioModule->bibtexOptionsLE->setEnabled(
-               biblioModule->bibtexCO->itemData(n).toString() != "default");
+       if (isBiblatex())
+               rescanTexStyles("bbx cbx");
+       else
+               rescanTexStyles("bst");
+}
+
+
+void GuiDocument::resetDefaultBibfile(string const & which)
+{
+       QString const engine =
+               biblioModule->citeEngineCO->itemData(
+                               biblioModule->citeEngineCO->currentIndex()).toString();
+
+       CiteEngineType const cet =
+               CiteEngineType(biblioModule->citeStyleCO->itemData(
+                                                         biblioModule->citeStyleCO->currentIndex()).toInt());
+
+       updateDefaultBiblio(theCiteEnginesList[fromqstr(engine)]->getDefaultBiblio(cet), which);
+}
+
+
+void GuiDocument::resetDefaultBbxBibfile()
+{
+       resetDefaultBibfile("bbx");
+}
+
+
+void GuiDocument::resetDefaultCbxBibfile()
+{
+       resetDefaultBibfile("cbx");
+}
+
+
+void GuiDocument::citeEngineChanged(int n)
+{
+       QString const engine =
+               biblioModule->citeEngineCO->itemData(n).toString();
+
+       vector<string> const engs =
+               theCiteEnginesList[fromqstr(engine)]->getEngineType();
+
+       updateCiteStyles(engs);
+       updateEngineDependends();
+       resetDefaultBibfile();
        biblioChanged();
 }
 
 
-void GuiDocument::setAuthorYear(bool authoryear)
+void GuiDocument::updateEngineDependends()
 {
-       if (authoryear)
-               biblioModule->citeStyleCO->setCurrentIndex(0);
+       bool const biblatex = isBiblatex();
+
+       // These are only useful with BibTeX
+       biblioModule->defaultBiblioCO->setEnabled(!biblatex);
+       biblioModule->bibtexStyleLA->setEnabled(!biblatex);
+       biblioModule->resetDefaultBiblioPB->setEnabled(!biblatex);
+       biblioModule->bibtopicCB->setEnabled(!biblatex);
+
+       // These are only useful with Biblatex
+       biblioModule->biblatexBbxCO->setEnabled(biblatex);
+       biblioModule->biblatexBbxLA->setEnabled(biblatex);
+       biblioModule->biblatexCbxCO->setEnabled(biblatex);
+       biblioModule->biblatexCbxLA->setEnabled(biblatex);
+       biblioModule->resetBbxPB->setEnabled(biblatex);
+       biblioModule->resetCbxPB->setEnabled(biblatex);
+       biblioModule->matchBbxPB->setEnabled(biblatex);
+
+       // These are useful with biblatex, jurabib and natbib
+       QString const engine =
+               biblioModule->citeEngineCO->itemData(
+                               biblioModule->citeEngineCO->currentIndex()).toString();
+       LyXCiteEngine const * ce = theCiteEnginesList[fromqstr(engine)];
+
+       bool const citepack = ce->requires("biblatex.sty") || ce->requires("jurabib.sty")
+                       || ce->requires("natbib.sty");
+       biblioModule->citePackageOptionsLE->setEnabled(citepack);
+       biblioModule->citePackageOptionsL->setEnabled(citepack);
+}
+
+
+void GuiDocument::citeStyleChanged()
+{
+       QString const engine =
+               biblioModule->citeEngineCO->itemData(
+                               biblioModule->citeEngineCO->currentIndex()).toString();
+       QString const currentDef = isBiblatex() ?
+               biblioModule->biblatexBbxCO->currentText()
+               : biblioModule->defaultBiblioCO->currentText();
+       if (theCiteEnginesList[fromqstr(engine)]->isDefaultBiblio(fromqstr(currentDef)))
+               resetDefaultBibfile();
+
        biblioChanged();
 }
 
 
-void GuiDocument::setNumerical(bool numerical)
+void GuiDocument::bibtexChanged(int n)
 {
-       if (numerical)
-               biblioModule->citeStyleCO->setCurrentIndex(1);
+       biblioModule->bibtexOptionsLE->setEnabled(
+               biblioModule->bibtexCO->itemData(n).toString() != "default");
        biblioChanged();
 }
 
 
+void GuiDocument::updateCiteStyles(vector<string> const & engs, CiteEngineType const & sel)
+{
+       biblioModule->citeStyleCO->clear();
+
+       vector<string>::const_iterator it  = engs.begin();
+       vector<string>::const_iterator end = engs.end();
+       for (; it != end; ++it) {
+               if (*it == "default")
+                       biblioModule->citeStyleCO->addItem(qt_("Basic numerical"),
+                                                          ENGINE_TYPE_DEFAULT);
+               else if (*it == "authoryear")
+                       biblioModule->citeStyleCO->addItem(qt_("Author-year"),
+                                                          ENGINE_TYPE_AUTHORYEAR);
+               else if (*it == "numerical")
+                       biblioModule->citeStyleCO->addItem(qt_("Author-number"),
+                                                          ENGINE_TYPE_NUMERICAL);
+       }
+       int i = biblioModule->citeStyleCO->findData(sel);
+       if (biblioModule->citeStyleCO->findData(sel) == -1)
+               i = 0;
+       biblioModule->citeStyleCO->setCurrentIndex(i);
+
+       biblioModule->citationStyleL->setEnabled(engs.size() > 1);
+       biblioModule->citeStyleCO->setEnabled(engs.size() > 1);
+}
+
+
 void GuiDocument::updateEngineType(string const & items, CiteEngineType const & sel)
 {
        engine_types_.clear();
@@ -2246,27 +2516,7 @@ void GuiDocument::updateEngineType(string const & items, CiteEngineType const &
                engine_types_.push_back(style);
        }
 
-       switch (sel) {
-               case ENGINE_TYPE_AUTHORYEAR:
-                       biblioModule->citeStyleCO->setCurrentIndex(0);
-                       break;
-               case ENGINE_TYPE_NUMERICAL:
-                       biblioModule->citeStyleCO->setCurrentIndex(1);
-                       break;
-       }
-
-       biblioModule->citationStyleL->setEnabled(nn > 1);
-       biblioModule->citeStyleCO->setEnabled(nn > 1);
-
-       if (nn != 1)
-               return;
-
-       // If the textclass allows only one of authoryear or numerical,
-       // we have no choice but to force that engine type.
-       if (engine_types_[0] == "authoryear")
-               biblioModule->citeStyleCO->setCurrentIndex(0);
-       else
-               biblioModule->citeStyleCO->setCurrentIndex(1);
+       updateCiteStyles(engine_types_, sel);
 }
 
 
@@ -2355,8 +2605,19 @@ void GuiDocument::modulesToParams(BufferParams & bp)
 void GuiDocument::modulesChanged()
 {
        modulesToParams(bp_);
+
+       if (applyPB->isEnabled() && nonModuleChanged_) {
+               int const ret = Alert::prompt(_("Unapplied changes"),
+                               _("Some changes in the dialog were not yet applied.\n"
+                               "If you do not apply now, they will be lost after this action."),
+                               1, 1, _("&Apply"), _("&Dismiss"));
+               if (ret == 0)
+                       applyView();
+       }
+
        bp_.makeDocumentClass();
        paramsToDialog();
+       changed();
 }
 
 
@@ -2472,20 +2733,18 @@ void GuiDocument::updateDefaultFormat()
        if (idx >= 0) {
                string const classname = fromqstr(latexModule->classCO->getData(idx));
                param_copy.setBaseClass(classname);
-               param_copy.makeDocumentClass();
+               param_copy.makeDocumentClass(true);
        }
        outputModule->defaultFormatCO->blockSignals(true);
        outputModule->defaultFormatCO->clear();
        outputModule->defaultFormatCO->addItem(qt_("Default"),
                                QVariant(QString("default")));
-       typedef vector<Format const *> Formats;
-       Formats formats = param_copy.exportableFormats(true);
-       sort(formats.begin(), formats.end(), Format::formatSorter);
-       Formats::const_iterator cit = formats.begin();
-       Formats::const_iterator end = formats.end();
-       for (; cit != end; ++cit)
-               outputModule->defaultFormatCO->addItem(qt_((*cit)->prettyname()),
-                               QVariant(toqstr((*cit)->name())));
+       FormatList const & formats =
+                               param_copy.exportableFormats(true);
+       for (Format const * f : formats)
+               outputModule->defaultFormatCO->addItem
+                       (toqstr(translateIfPossible(f->prettyname())),
+                        QVariant(toqstr(f->name())));
        outputModule->defaultFormatCO->blockSignals(false);
 }
 
@@ -2510,22 +2769,28 @@ void GuiDocument::applyView()
        bp_.use_refstyle  = latexModule->refstyleCB->isChecked();
 
        // biblio
-       if (biblioModule->citeNatbibRB->isChecked())
-               bp_.setCiteEngine("natbib");
-       else if (biblioModule->citeJurabibRB->isChecked())
-               bp_.setCiteEngine("jurabib");
+       string const engine =
+               fromqstr(biblioModule->citeEngineCO->itemData(
+                               biblioModule->citeEngineCO->currentIndex()).toString());
+       bp_.setCiteEngine(engine);
+
+       CiteEngineType const style = CiteEngineType(biblioModule->citeStyleCO->itemData(
+               biblioModule->citeStyleCO->currentIndex()).toInt());
+       if (theCiteEnginesList[engine]->hasEngineType(style))
+               bp_.setCiteEngineType(style);
        else
-               bp_.setCiteEngine("basic");
+               bp_.setCiteEngineType(ENGINE_TYPE_DEFAULT);
 
-       if (biblioModule->citeStyleCO->currentIndex())
-               bp_.setCiteEngineType(ENGINE_TYPE_NUMERICAL);
-       else
-               bp_.setCiteEngineType(ENGINE_TYPE_AUTHORYEAR);
+       bp_.splitbib(biblioModule->bibtopicCB->isChecked());
 
-       bp_.use_bibtopic =
-               biblioModule->bibtopicCB->isChecked();
+       bp_.multibib = fromqstr(biblioModule->bibunitsCO->itemData(
+                               biblioModule->bibunitsCO->currentIndex()).toString());
 
-       bp_.biblio_style = fromqstr(biblioModule->bibtexStyleLE->text());
+       bp_.setDefaultBiblioStyle(fromqstr(biblioModule->defaultBiblioCO->currentText()));
+
+       bp_.biblatex_bibstyle = fromqstr(biblioModule->biblatexBbxCO->currentText());
+       bp_.biblatex_citestyle = fromqstr(biblioModule->biblatexCbxCO->currentText());
+       bp_.biblio_opts = fromqstr(biblioModule->citePackageOptionsLE->text());
 
        string const bibtex_command =
                fromqstr(biblioModule->bibtexCO->itemData(
@@ -2574,12 +2839,20 @@ void GuiDocument::applyView()
                }
        }
 
-       bp_.quotes_language = (InsetQuotes::QuoteLanguage) langModule->quoteStyleCO->itemData(
+       bp_.quotes_style = (InsetQuotesParams::QuoteStyle) langModule->quoteStyleCO->itemData(
                langModule->quoteStyleCO->currentIndex()).toInt();
+       bp_.dynamic_quotes = langModule->dynamicQuotesCB->isChecked();
 
-       QString const lang = langModule->languageCO->itemData(
+       QString const langname = langModule->languageCO->itemData(
                langModule->languageCO->currentIndex()).toString();
-       bp_.language = lyx::languages.getLanguage(fromqstr(lang));
+       Language const * newlang = lyx::languages.getLanguage(fromqstr(langname));
+       Cursor & cur = const_cast<BufferView *>(bufferview())->cursor();
+       // If current cursor language was the document language, then update it too.
+       if (cur.current_font.language() == bp_.language) {
+               cur.current_font.setLanguage(newlang);
+               cur.real_current_font.setLanguage(newlang);
+       }
+       bp_.language = newlang;
 
        QString const pack = langModule->languagePackageCO->itemData(
                langModule->languagePackageCO->currentIndex()).toString();
@@ -2645,7 +2918,7 @@ void GuiDocument::applyView()
                if (rb->isChecked())
                        bp_.use_package(it->first, BufferParams::package_off);
        }
-
+       
        // Page Layout
        if (pageLayoutModule->pagestyleCO->currentIndex() == 0)
                bp_.pagestyle = "default";
@@ -2689,19 +2962,19 @@ void GuiDocument::applyView()
                bp_.paragraph_separation = BufferParams::ParagraphIndentSeparation;
                switch (textLayoutModule->indentCO->currentIndex()) {
                case 0:
-                       bp_.setIndentation(HSpace(HSpace::DEFAULT));
+                       bp_.setParIndent(Length());
                        break;
                case 1: {
-                       HSpace indent = HSpace(
+                       Length indent(
                                widgetsToLength(textLayoutModule->indentLE,
                                textLayoutModule->indentLengthCO)
                                );
-                       bp_.setIndentation(indent);
+                       bp_.setParIndent(indent);
                        break;
                        }
                default:
                        // this should never happen
-                       bp_.setIndentation(HSpace(HSpace::DEFAULT));
+                       bp_.setParIndent(Length());
                        break;
                }
        } else {
@@ -2733,6 +3006,25 @@ void GuiDocument::applyView()
                }
        }
 
+       bp_.is_math_indent = textLayoutModule->MathIndentCB->isChecked();
+       if (bp_.is_math_indent) {
+               // if math is indented
+               switch (textLayoutModule->MathIndentCO->currentIndex()) {
+               case 0:
+                       bp_.math_indentation = "default";
+                       break;
+               case 1:
+                       bp_.math_indentation = widgetsToLength(textLayoutModule->MathIndentLE,
+                               textLayoutModule->MathIndentLengthCO);
+                       break;
+               default:
+                       // this should never happen
+                       bp_.math_indentation = "default";
+                       break;
+               }
+       } else
+               bp_.math_indentation = "default";
+
        bp_.options =
                fromqstr(latexModule->optionsLE->text());
 
@@ -2764,7 +3056,7 @@ void GuiDocument::applyView()
        bp_.listings_params =
                InsetListingsParams(fromqstr(listingsModule->listingsED->toPlainText())).params();
 
-       // output
+       // Formats
        bp_.default_output_format = fromqstr(outputModule->defaultFormatCO->itemData(
                outputModule->defaultFormatCO->currentIndex()).toString());
 
@@ -2772,7 +3064,7 @@ void GuiDocument::applyView()
        bp_.useNonTeXFonts = nontexfonts;
 
        bp_.output_sync = outputModule->outputsyncCB->isChecked();
-       
+
        bp_.output_sync_macro = fromqstr(outputModule->synccustomCB->currentText());
 
        int mathfmt = outputModule->mathoutCB->currentIndex();
@@ -2784,23 +3076,31 @@ void GuiDocument::applyView()
        bp_.html_be_strict = outputModule->strictCB->isChecked();
        bp_.html_css_as_file = outputModule->cssCB->isChecked();
        bp_.html_math_img_scale = outputModule->mathimgSB->value();
+       bp_.display_pixel_ratio = theGuiApp()->pixelRatio();
+
+       bp_.save_transient_properties =
+               outputModule->saveTransientPropertiesCB->isChecked();
 
        // fonts
-       bp_.fonts_roman =
+       bp_.fonts_roman[nontexfonts] =
                fromqstr(fontModule->fontsRomanCO->
                        itemData(fontModule->fontsRomanCO->currentIndex()).toString());
+       bp_.fonts_roman[!nontexfonts] = fromqstr(fontModule->font_roman);
 
-       bp_.fonts_sans =
+       bp_.fonts_sans[nontexfonts] =
                fromqstr(fontModule->fontsSansCO->
                        itemData(fontModule->fontsSansCO->currentIndex()).toString());
+       bp_.fonts_sans[!nontexfonts] = fromqstr(fontModule->font_sans);
 
-       bp_.fonts_typewriter =
+       bp_.fonts_typewriter[nontexfonts] =
                fromqstr(fontModule->fontsTypewriterCO->
                        itemData(fontModule->fontsTypewriterCO->currentIndex()).toString());
+       bp_.fonts_typewriter[!nontexfonts] = fromqstr(fontModule->font_typewriter);
 
-       bp_.fonts_math =
+       bp_.fonts_math[nontexfonts] =
                fromqstr(fontModule->fontsMathCO->
                        itemData(fontModule->fontsMathCO->currentIndex()).toString());
+       bp_.fonts_math[!nontexfonts] = fromqstr(fontModule->font_math);
 
        QString const fontenc =
                fontModule->fontencCO->itemData(fontModule->fontencCO->currentIndex()).toString();
@@ -2812,9 +3112,14 @@ void GuiDocument::applyView()
        bp_.fonts_cjk =
                fromqstr(fontModule->cjkFontLE->text());
 
-       bp_.fonts_sans_scale = fontModule->scaleSansSB->value();
+       bp_.use_microtype = fontModule->microtypeCB->isChecked();
+       bp_.use_dash_ligatures = fontModule->dashesCB->isChecked();
+
+       bp_.fonts_sans_scale[nontexfonts] = fontModule->scaleSansSB->value();
+       bp_.fonts_sans_scale[!nontexfonts] = fontModule->font_sf_scale;
 
-       bp_.fonts_typewriter_scale = fontModule->scaleTypewriterSB->value();
+       bp_.fonts_typewriter_scale[nontexfonts] = fontModule->scaleTypewriterSB->value();
+       bp_.fonts_typewriter_scale[!nontexfonts] = fontModule->font_tt_scale;
 
        bp_.fonts_expert_sc = fontModule->fontScCB->isChecked();
 
@@ -2894,6 +3199,9 @@ void GuiDocument::applyView()
                pdf.pagemode.clear();
        pdf.quoted_options = pdf.quoted_options_check(
                                fromqstr(pdfSupportModule->optionsLE->text()));
+
+       // reset tracker
+       nonModuleChanged_ = false;
 }
 
 
@@ -2913,25 +3221,44 @@ void GuiDocument::paramsToDialog()
        // biblio
        string const cite_engine = bp_.citeEngine().list().front();
 
-       biblioModule->citeDefaultRB->setChecked(
-               cite_engine == "basic");
-
-       biblioModule->citeJurabibRB->setChecked(
-               cite_engine == "jurabib");
+       biblioModule->citeEngineCO->setCurrentIndex(
+               biblioModule->citeEngineCO->findData(toqstr(cite_engine)));
 
-       biblioModule->citeNatbibRB->setChecked(
-               cite_engine == "natbib");
+       updateEngineType(documentClass().opt_enginetype(),
+               bp_.citeEngineType());
 
        biblioModule->citeStyleCO->setCurrentIndex(
-               bp_.citeEngineType() == ENGINE_TYPE_NUMERICAL);
+               biblioModule->citeStyleCO->findData(bp_.citeEngineType()));
+
+       biblioModule->bibtopicCB->setChecked(bp_.splitbib());
+
+       biblioModule->bibunitsCO->clear();
+       biblioModule->bibunitsCO->addItem(qt_("No"), QString());
+       if (documentClass().hasLaTeXLayout("part"))
+               biblioModule->bibunitsCO->addItem(qt_("per part"), toqstr("part"));
+       if (documentClass().hasLaTeXLayout("chapter"))
+               biblioModule->bibunitsCO->addItem(qt_("per chapter"), toqstr("chapter"));
+       if (documentClass().hasLaTeXLayout("section"))
+               biblioModule->bibunitsCO->addItem(qt_("per section"), toqstr("section"));
+       if (documentClass().hasLaTeXLayout("subsection"))
+               biblioModule->bibunitsCO->addItem(qt_("per subsection"), toqstr("subsection"));
+       biblioModule->bibunitsCO->addItem(qt_("per child document"), toqstr("child"));
+
+       int const mbpos = biblioModule->bibunitsCO->findData(toqstr(bp_.multibib));
+       if (mbpos != -1)
+               biblioModule->bibunitsCO->setCurrentIndex(mbpos);
+       else
+               biblioModule->bibunitsCO->setCurrentIndex(0);
 
-       updateEngineType(documentClass().opt_enginetype(),
-               bp_.citeEngineType());
+       updateEngineDependends();
 
-       biblioModule->bibtopicCB->setChecked(
-               bp_.use_bibtopic);
+       if (isBiblatex()) {
+               updateDefaultBiblio(bp_.biblatex_bibstyle, "bbx");
+               updateDefaultBiblio(bp_.biblatex_citestyle, "cbx");
+       } else
+               updateDefaultBiblio(bp_.defaultBiblioStyle());
 
-       biblioModule->bibtexStyleLE->setText(toqstr(bp_.biblio_style));
+       biblioModule->citePackageOptionsLE->setText(toqstr(bp_.biblio_opts));
 
        string command;
        string options =
@@ -2954,15 +3281,21 @@ void GuiDocument::paramsToDialog()
        biblioChanged_ = false;
 
        // indices
-       indicesModule->update(bp_);
+       // We may be called when there is no Buffer, e.g., when 
+       // the last view has just been closed.
+       bool const isReadOnly = isBufferAvailable() ? buffer().isReadonly() : false;
+       indicesModule->update(bp_, isReadOnly);
 
        // language & quotes
        int const pos = langModule->languageCO->findData(toqstr(
                bp_.language->lang()));
        langModule->languageCO->setCurrentIndex(pos);
 
+       updateQuoteStyles();
+
        langModule->quoteStyleCO->setCurrentIndex(
-               bp_.quotes_language);
+               langModule->quoteStyleCO->findData(bp_.quotes_style));
+       langModule->dynamicQuotesCB->setChecked(bp_.dynamic_quotes);
 
        bool default_enc = true;
        if (bp_.inputenc != "auto") {
@@ -3055,6 +3388,20 @@ void GuiDocument::paramsToDialog()
                latexModule->psdriverCO->setCurrentIndex(nitem);
        updateModuleInfo();
 
+       // math
+       if (bp_.is_math_indent) {
+               textLayoutModule->MathIndentCB->setChecked(bp_.is_math_indent);
+               int MathIndent = 0;
+               if (bp_.math_indentation != "default") {
+                       lengthToWidgets(textLayoutModule->MathIndentLE,
+                       textLayoutModule->MathIndentLengthCO,
+                       bp_.math_indentation, default_unit);
+                       MathIndent = 1;
+               }
+               textLayoutModule->MathIndentCO->setCurrentIndex(MathIndent);
+               setMathIndent(MathIndent);
+       }
+
        map<string, string> const & packages = BufferParams::auto_packages();
        for (map<string, string>::const_iterator it = packages.begin();
             it != packages.end(); ++it) {
@@ -3104,12 +3451,12 @@ void GuiDocument::paramsToDialog()
 
        if (bp_.paragraph_separation == BufferParams::ParagraphIndentSeparation) {
                textLayoutModule->indentRB->setChecked(true);
-               string indentation = bp_.getIndentation().asLyXCommand();
+               string parindent = bp_.getParIndent().asString();
                int indent = 0;
-               if (indentation != "default") {
+               if (!parindent.empty()) {
                        lengthToWidgets(textLayoutModule->indentLE,
-                       textLayoutModule->indentLengthCO,
-                       indentation, default_unit);
+                                       textLayoutModule->indentLengthCO,
+                                       parindent, default_unit);
                        indent = 1;
                }
                textLayoutModule->indentCO->setCurrentIndex(indent);
@@ -3214,46 +3561,56 @@ void GuiDocument::paramsToDialog()
        listingsModule->listingsED->setPlainText(toqstr(lstparams));
 
        // Fonts
+       // some languages only work with polyglossia/XeTeX
+       Language const * lang = lyx::languages.getLanguage(
+               fromqstr(langModule->languageCO->itemData(
+                       langModule->languageCO->currentIndex()).toString()));
+       bool const need_fontspec =
+               lang->babel().empty() && !lang->polyglossia().empty();
        bool const os_fonts_available =
                bp_.baseClass()->outputType() == lyx::LATEX
                && LaTeXFeatures::isAvailable("fontspec");
-       fontModule->osFontsCB->setEnabled(os_fonts_available);
+       fontModule->osFontsCB->setEnabled(os_fonts_available && !need_fontspec);
        fontModule->osFontsCB->setChecked(
-               os_fonts_available && bp_.useNonTeXFonts);
+               (os_fonts_available && bp_.useNonTeXFonts) || need_fontspec);
        updateFontsize(documentClass().opt_fontsize(),
                        bp_.fontsize);
 
-       QString font = toqstr(bp_.fonts_roman);
+       QString font = toqstr(bp_.fontsRoman());
        int rpos = fontModule->fontsRomanCO->findData(font);
        if (rpos == -1) {
                rpos = fontModule->fontsRomanCO->count();
                fontModule->fontsRomanCO->addItem(font + qt_(" (not installed)"), font);
        }
        fontModule->fontsRomanCO->setCurrentIndex(rpos);
+       fontModule->font_roman = toqstr(bp_.fonts_roman[!bp_.useNonTeXFonts]);
 
-       font = toqstr(bp_.fonts_sans);
+       font = toqstr(bp_.fontsSans());
        int spos = fontModule->fontsSansCO->findData(font);
        if (spos == -1) {
                spos = fontModule->fontsSansCO->count();
                fontModule->fontsSansCO->addItem(font + qt_(" (not installed)"), font);
        }
        fontModule->fontsSansCO->setCurrentIndex(spos);
+       fontModule->font_sans = toqstr(bp_.fonts_sans[!bp_.useNonTeXFonts]);
 
-       font = toqstr(bp_.fonts_typewriter);
+       font = toqstr(bp_.fontsTypewriter());
        int tpos = fontModule->fontsTypewriterCO->findData(font);
        if (tpos == -1) {
                tpos = fontModule->fontsTypewriterCO->count();
                fontModule->fontsTypewriterCO->addItem(font + qt_(" (not installed)"), font);
        }
        fontModule->fontsTypewriterCO->setCurrentIndex(tpos);
+       fontModule->font_typewriter = toqstr(bp_.fonts_typewriter[!bp_.useNonTeXFonts]);
 
-       font = toqstr(bp_.fonts_math);
+       font = toqstr(bp_.fontsMath());
        int mpos = fontModule->fontsMathCO->findData(font);
        if (mpos == -1) {
                mpos = fontModule->fontsMathCO->count();
                fontModule->fontsMathCO->addItem(font + qt_(" (not installed)"), font);
        }
        fontModule->fontsMathCO->setCurrentIndex(mpos);
+       fontModule->font_math = toqstr(bp_.fonts_math[!bp_.useNonTeXFonts]);
 
        if (bp_.useNonTeXFonts && os_fonts_available) {
                fontModule->fontencLA->setEnabled(false);
@@ -3273,11 +3630,16 @@ void GuiDocument::paramsToDialog()
                        toqstr(bp_.fonts_cjk));
        else
                fontModule->cjkFontLE->setText(QString());
+       
+       fontModule->microtypeCB->setChecked(bp_.use_microtype);
+       fontModule->dashesCB->setChecked(bp_.use_dash_ligatures);
 
        fontModule->fontScCB->setChecked(bp_.fonts_expert_sc);
        fontModule->fontOsfCB->setChecked(bp_.fonts_old_figures);
-       fontModule->scaleSansSB->setValue(bp_.fonts_sans_scale);
-       fontModule->scaleTypewriterSB->setValue(bp_.fonts_typewriter_scale);
+       fontModule->scaleSansSB->setValue(bp_.fontsSansScale());
+       fontModule->font_sf_scale = bp_.fonts_sans_scale[!bp_.useNonTeXFonts];
+       fontModule->scaleTypewriterSB->setValue(bp_.fontsTypewriterScale());
+       fontModule->font_tt_scale = bp_.fonts_typewriter_scale[!bp_.useNonTeXFonts];
 
        int nn = findToken(GuiDocument::fontfamilies, bp_.fonts_default_family);
        if (nn >= 0)
@@ -3292,7 +3654,7 @@ void GuiDocument::paramsToDialog()
                fontModule->fontencLE->setText(toqstr(bp_.fontenc));
        }
 
-       // Output
+       // Formats
        // This must be set _after_ fonts since updateDefaultFormat()
        // checks osFontsCB settings.
        // update combobox with formats
@@ -3312,6 +3674,9 @@ void GuiDocument::paramsToDialog()
        outputModule->strictCB->setChecked(bp_.html_be_strict);
        outputModule->cssCB->setChecked(bp_.html_css_as_file);
 
+       outputModule->saveTransientPropertiesCB
+               ->setChecked(bp_.save_transient_properties);
+
        // paper
        bool const extern_geometry =
                documentClass().provides("geometry");
@@ -3407,6 +3772,9 @@ void GuiDocument::paramsToDialog()
 
        // clear changed branches cache
        changedBranches_.clear();
+
+       // reset tracker
+       nonModuleChanged_ = false;
 }
 
 
@@ -3421,12 +3789,16 @@ void GuiDocument::saveDocDefault()
 void GuiDocument::updateAvailableModules()
 {
        modules_av_model_.clear();
-       list<modInfoStruct> const & modInfoList = getModuleInfo();
-       list<modInfoStruct>::const_iterator mit = modInfoList.begin();
-       list<modInfoStruct>::const_iterator men = modInfoList.end();
-       for (int i = 0; mit != men; ++mit, ++i)
-               modules_av_model_.insertRow(i, mit->name, mit->id,
-                               mit->description);
+       list<modInfoStruct> modInfoList = getModuleInfo();
+       // Sort names according to the locale
+       modInfoList.sort([](modInfoStruct const & a, modInfoStruct const & b) {
+                       return 0 < b.name.localeAwareCompare(a.name);
+               });
+       int i = 0;
+       for (modInfoStruct const & m : modInfoList) {
+               modules_av_model_.insertRow(i, m.name, m.id, m.description);
+               ++i;
+       }
 }
 
 
@@ -3434,11 +3806,11 @@ void GuiDocument::updateSelectedModules()
 {
        modules_sel_model_.clear();
        list<modInfoStruct> const selModList = getSelectedModules();
-       list<modInfoStruct>::const_iterator mit = selModList.begin();
-       list<modInfoStruct>::const_iterator men = selModList.end();
-       for (int i = 0; mit != men; ++mit, ++i)
-               modules_sel_model_.insertRow(i, mit->name, mit->id,
-                               mit->description);
+       int i = 0;
+       for (modInfoStruct const & m : selModList) {
+               modules_sel_model_.insertRow(i, m.name, m.id, m.description);
+               ++i;
+       }
 }
 
 
@@ -3457,14 +3829,13 @@ void GuiDocument::updateIncludeonlys()
                masterChildModule->childrenTW->setEnabled(true);
                masterChildModule->maintainAuxCB->setEnabled(true);
        }
-       QTreeWidgetItem * item = 0;
        ListOfBuffers children = buffer().getChildren();
        ListOfBuffers::const_iterator it  = children.begin();
        ListOfBuffers::const_iterator end = children.end();
        bool has_unincluded = false;
        bool all_unincluded = true;
        for (; it != end; ++it) {
-               item = new QTreeWidgetItem(masterChildModule->childrenTW);
+               QTreeWidgetItem * item = new QTreeWidgetItem(masterChildModule->childrenTW);
                // FIXME Unicode
                string const name =
                        to_utf8(makeRelPath(from_utf8((*it)->fileName().absFileName()),
@@ -3490,6 +3861,154 @@ void GuiDocument::updateIncludeonlys()
 }
 
 
+bool GuiDocument::isBiblatex() const
+{
+       QString const engine =
+               biblioModule->citeEngineCO->itemData(
+                               biblioModule->citeEngineCO->currentIndex()).toString();
+
+       return theCiteEnginesList[fromqstr(engine)]->getCiteFramework() == "biblatex";
+}
+
+
+void GuiDocument::updateDefaultBiblio(string const & style,
+                                     string const & which)
+{
+       QString const bibstyle = toqstr(style);
+       biblioModule->defaultBiblioCO->clear();
+
+       int item_nr = -1;
+
+       if (isBiblatex()) {
+               if (which != "cbx") {
+                       // First the bbx styles
+                       biblioModule->biblatexBbxCO->clear();
+                       QStringList str = texFileList("bbxFiles.lst");
+                       // test whether we have a valid list, otherwise run rescan
+                       if (str.isEmpty()) {
+                               rescanTexStyles("bbx");
+                               str = texFileList("bbxFiles.lst");
+                       }
+                       for (int i = 0; i != str.size(); ++i)
+                               str[i] = onlyFileName(str[i]);
+                       // sort on filename only (no path)
+                       str.sort();
+
+                       for (int i = 0; i != str.count(); ++i) {
+                               QString item = changeExtension(str[i], "");
+                               if (item == bibstyle)
+                                       item_nr = i;
+                               biblioModule->biblatexBbxCO->addItem(item);
+                       }
+
+                       if (item_nr == -1 && !bibstyle.isEmpty()) {
+                               biblioModule->biblatexBbxCO->addItem(bibstyle);
+                               item_nr = biblioModule->biblatexBbxCO->count() - 1;
+                       }
+
+                       if (item_nr != -1)
+                               biblioModule->biblatexBbxCO->setCurrentIndex(item_nr);
+                       else
+                               biblioModule->biblatexBbxCO->clearEditText();
+               }
+
+               if (which != "bbx") {
+                       // now the cbx styles
+                       biblioModule->biblatexCbxCO->clear();
+                       QStringList str = texFileList("cbxFiles.lst");
+                       // test whether we have a valid list, otherwise run rescan
+                       if (str.isEmpty()) {
+                               rescanTexStyles("cbx");
+                               str = texFileList("cbxFiles.lst");
+                       }
+                       for (int i = 0; i != str.size(); ++i)
+                               str[i] = onlyFileName(str[i]);
+                       // sort on filename only (no path)
+                       str.sort();
+
+                       for (int i = 0; i != str.count(); ++i) {
+                               QString item = changeExtension(str[i], "");
+                               if (item == bibstyle)
+                                       item_nr = i;
+                               biblioModule->biblatexCbxCO->addItem(item);
+                       }
+
+                       if (item_nr == -1 && !bibstyle.isEmpty()) {
+                               biblioModule->biblatexCbxCO->addItem(bibstyle);
+                               item_nr = biblioModule->biblatexCbxCO->count() - 1;
+                       }
+
+                       if (item_nr != -1)
+                               biblioModule->biblatexCbxCO->setCurrentIndex(item_nr);
+                       else
+                               biblioModule->biblatexCbxCO->clearEditText();
+               }
+       } else {// BibTeX
+               biblioModule->biblatexBbxCO->clear();
+               biblioModule->biblatexCbxCO->clear();
+               QStringList str = texFileList("bstFiles.lst");
+               // test whether we have a valid list, otherwise run rescan
+               if (str.isEmpty()) {
+                       rescanTexStyles("bst");
+                       str = texFileList("bstFiles.lst");
+               }
+               for (int i = 0; i != str.size(); ++i)
+                       str[i] = onlyFileName(str[i]);
+               // sort on filename only (no path)
+               str.sort();
+
+               for (int i = 0; i != str.count(); ++i) {
+                       QString item = changeExtension(str[i], "");
+                       if (item == bibstyle)
+                               item_nr = i;
+                       biblioModule->defaultBiblioCO->addItem(item);
+               }
+
+               if (item_nr == -1 && !bibstyle.isEmpty()) {
+                       biblioModule->defaultBiblioCO->addItem(bibstyle);
+                       item_nr = biblioModule->defaultBiblioCO->count() - 1;
+               }
+
+               if (item_nr != -1)
+                       biblioModule->defaultBiblioCO->setCurrentIndex(item_nr);
+               else
+                       biblioModule->defaultBiblioCO->clearEditText();
+       }
+
+       updateResetDefaultBiblio();
+}
+
+
+void GuiDocument::updateResetDefaultBiblio()
+{
+       QString const engine =
+               biblioModule->citeEngineCO->itemData(
+                               biblioModule->citeEngineCO->currentIndex()).toString();
+       CiteEngineType const cet =
+               CiteEngineType(biblioModule->citeStyleCO->itemData(
+                                                         biblioModule->citeStyleCO->currentIndex()).toInt());
+
+       string const defbib = theCiteEnginesList[fromqstr(engine)]->getDefaultBiblio(cet);
+       if (isBiblatex()) {
+               QString const bbx = biblioModule->biblatexBbxCO->currentText();
+               QString const cbx = biblioModule->biblatexCbxCO->currentText();
+               biblioModule->resetCbxPB->setEnabled(defbib != fromqstr(cbx));
+               biblioModule->resetBbxPB->setEnabled(defbib != fromqstr(bbx));
+               biblioModule->matchBbxPB->setEnabled(bbx != cbx && !cbx.isEmpty()
+                       && biblioModule->biblatexBbxCO->findText(cbx) != -1);
+       } else
+               biblioModule->resetDefaultBiblioPB->setEnabled(
+                       defbib != fromqstr(biblioModule->defaultBiblioCO->currentText()));
+}
+
+
+void GuiDocument::matchBiblatexStyles()
+{
+       updateDefaultBiblio(fromqstr(biblioModule->biblatexCbxCO->currentText()), "bbx");
+       biblioChanged();
+}
+
+
 void GuiDocument::updateContents()
 {
        // Nothing to do here as the document settings is not cursor dependant.
@@ -3547,6 +4066,14 @@ bool GuiDocument::isValid()
                        textLayoutModule->indentCO->currentIndex() != 1 ||
                        // or else a length has been given
                        !textLayoutModule->indentLE->text().isEmpty()
+               ) &&
+               (
+                       // if we're asking for indentation
+                       !textLayoutModule->MathIndentCB->isChecked() ||
+                       // then either we haven't chosen custom
+                       textLayoutModule->MathIndentCO->currentIndex() != 1 ||
+                       // or else a length has been given
+                       !textLayoutModule->MathIndentLE->text().isEmpty()
                );
 }
 
@@ -3601,20 +4128,18 @@ list<GuiDocument::modInfoStruct> const & GuiDocument::getModuleInfo()
 
 
 list<GuiDocument::modInfoStruct> const
-               GuiDocument::makeModuleInfo(LayoutModuleList const & mods)
+GuiDocument::makeModuleInfo(LayoutModuleList const & mods)
 {
-       LayoutModuleList::const_iterator it =  mods.begin();
-       LayoutModuleList::const_iterator end = mods.end();
        list<modInfoStruct> mInfo;
-       for (; it != end; ++it) {
+       for (string const & name : mods) {
                modInfoStruct m;
-               m.id = *it;
-               LyXModule const * const mod = theModuleList[*it];
+               LyXModule const * const mod = theModuleList[name];
                if (mod)
-                       // FIXME Unicode
-                       m.name = toqstr(translateIfPossible(from_utf8(mod->getName())));
-               else
-                       m.name = toqstr(*it) + toqstr(" (") + qt_("Not Found") + toqstr(")");
+                       m = modInfo(*mod);
+               else {
+                       m.id = name;
+                       m.name = toqstr(name + " (") + qt_("Not Found") + toqstr(")");
+               }
                mInfo.push_back(m);
        }
        return mInfo;
@@ -3640,11 +4165,11 @@ DocumentClass const & GuiDocument::documentClass() const
 
 
 static void dispatch_bufferparams(Dialog const & dialog,
-       BufferParams const & bp, FuncCode lfun)
+       BufferParams const & bp, FuncCode lfun, Buffer const * buf)
 {
        ostringstream ss;
        ss << "\\begin_header\n";
-       bp.writeFile(ss);
+       bp.writeFile(ss, buf);
        ss << "\\end_header\n";
        dialog.dispatch(FuncRequest(lfun, ss.str()));
 }
@@ -3652,12 +4177,17 @@ static void dispatch_bufferparams(Dialog const & dialog,
 
 void GuiDocument::dispatchParams()
 {
+       // We need a non-const buffer object.
+       Buffer & buf = const_cast<BufferView *>(bufferview())->buffer();
+       // There may be several undo records; group them (bug #8998)
+       buf.undo().beginUndoGroup();
+
        // This must come first so that a language change is correctly noticed
        setLanguage();
 
        // Apply the BufferParams. Note that this will set the base class
        // and then update the buffer's layout.
-       dispatch_bufferparams(*this, params(), LFUN_BUFFER_PARAMS_APPLY);
+       dispatch_bufferparams(*this, params(), LFUN_BUFFER_PARAMS_APPLY, &buffer());
 
        if (!params().master.empty()) {
                FileName const master_file = support::makeAbsPath(params().master,
@@ -3693,10 +4223,6 @@ void GuiDocument::dispatchParams()
                        docstring const str = current_branch + ' ' + from_ascii(x11hexname);
                        dispatch(FuncRequest(LFUN_SET_COLOR, str));
                }
-
-               // Open insets of selected branches, close deselected ones
-               dispatch(FuncRequest(LFUN_INSET_FORALL,
-                       "Branch inset-toggle assign"));
        }
        // rename branches in the document
        executeBranchRenaming();
@@ -3721,6 +4247,10 @@ void GuiDocument::dispatchParams()
        // If we used an LFUN, we would not need these two lines:
        BufferView * bv = const_cast<BufferView *>(bufferview());
        bv->processUpdateFlags(Update::Force | Update::FitCursor);
+
+       // Don't forget to close the group. Note that it is important
+       // to check that there is no early return in the method.
+       buf.undo().endUndoGroup();
 }
 
 
@@ -3737,7 +4267,7 @@ void GuiDocument::setLanguage() const
 
 void GuiDocument::saveAsDefault() const
 {
-       dispatch_bufferparams(*this, params(), LFUN_BUFFER_SAVE_AS_DEFAULT);
+       dispatch_bufferparams(*this, params(), LFUN_BUFFER_SAVE_AS_DEFAULT, &buffer());
 }
 
 
@@ -3797,27 +4327,35 @@ bool GuiDocument::hasMonolithicExpertSet(QString const & font) const
 }
 
 
+//static
+GuiDocument::modInfoStruct GuiDocument::modInfo(LyXModule const & mod)
+{
+       // FIXME Unicode: docstrings would be better for these parameters but this
+       // change requires a lot of others
+       modInfoStruct m;
+       m.id = mod.getID();
+       m.name = toqstr(translateIfPossible(from_utf8(mod.getName())));
+       QString desc = toqstr(translateIfPossible(from_utf8(mod.getDescription())));
+       // Find the first sentence of the description
+       QTextBoundaryFinder bf(QTextBoundaryFinder::Sentence, desc);
+       int pos = bf.toNextBoundary();
+       if (pos > 0)
+               desc.truncate(pos);
+       QString modulename = QString(qt_("(Module name: %1)")).arg(toqstr(m.id));
+       // Tooltip is the desc followed by the module name
+       m.description = QString("%1<i>%2</i>")
+               .arg(desc.isEmpty() ? QString() : QString("<p>%1</p>").arg(desc),
+                    modulename);
+       return m;
+}
+
+
 void GuiDocument::loadModuleInfo()
 {
        moduleNames_.clear();
-       LyXModuleList::const_iterator it  = theModuleList.begin();
-       LyXModuleList::const_iterator end = theModuleList.end();
-       for (; it != end; ++it) {
-               modInfoStruct m;
-               m.id = it->getID();
-               // FIXME Unicode
-               m.name = toqstr(translateIfPossible(from_utf8(it->getName())));
-               // this is supposed to give us the first sentence of the description
-               // FIXME Unicode
-               QString desc =
-                       toqstr(translateIfPossible(from_utf8(it->getDescription())));
-               int const pos = desc.indexOf(".");
-               if (pos > 0)
-                       desc.truncate(pos + 1);
-               m.description = desc;
-               if (it->category().substr(0, 8) != "Citation")
-                       moduleNames_.push_back(m);
-       }
+       for (LyXModule const & mod : theModuleList)
+               if (mod.category().substr(0, 8) != "Citation")
+                       moduleNames_.push_back(modInfo(mod));
 }