]> git.lyx.org Git - lyx.git/blobdiff - src/frontends/qt/GuiDocument.cpp
Fix readability
[lyx.git] / src / frontends / qt / GuiDocument.cpp
index c62e955859156bb84d4171a8d7c1092a4e8ca798..b16e8923bc8ef36a7d3f336f32e21f4889a6802a 100644 (file)
@@ -4,7 +4,7 @@
  * Licence details can be found in the file COPYING.
  *
  * \author Edwin Leuven
- * \author Richard Heck (modules)
+ * \author Richard Kimberly Heck (modules)
  *
  * Full author contact details are available in file CREDITS.
  */
 
 #include "GuiDocument.h"
 
+#include "BulletsModule.h"
 #include "CategorizedCombo.h"
+#include "FancyLineEdit.h"
 #include "GuiApplication.h"
 #include "GuiBranches.h"
 #include "GuiIndices.h"
+#include "GuiView.h"
 #include "GuiSelectionManager.h"
-#include "LaTeXHighlighter.h"
-#include "LengthCombo.h"
-#include "PanelStack.h"
 #include "Validator.h"
 
 #include "LayoutFile.h"
 #include "BranchList.h"
 #include "buffer_funcs.h"
 #include "Buffer.h"
-#include "BufferParams.h"
 #include "BufferView.h"
 #include "CiteEnginesList.h"
 #include "Color.h"
@@ -47,7 +46,6 @@
 #include "LayoutModuleList.h"
 #include "LyXRC.h"
 #include "ModuleList.h"
-#include "OutputParams.h"
 #include "PDFOptions.h"
 #include "qt_helpers.h"
 #include "Session.h"
@@ -57,6 +55,7 @@
 #include "VSpace.h"
 
 #include "insets/InsetListingsParams.h"
+#include "insets/InsetQuotes.h"
 
 #include "support/debug.h"
 #include "support/docstream.h"
@@ -73,7 +72,6 @@
 #include <QAbstractItemModel>
 #include <QButtonGroup>
 #include <QColor>
-#include <QColorDialog>
 #include <QCloseEvent>
 #include <QDirIterator>
 #include <QFontDatabase>
 #include <sstream>
 #include <vector>
 
-#ifdef IN
-#undef IN
-#endif
-
 
-// a style sheet for buttons
-// this is for example used for the background color setting button
-static inline QString colorButtonStyleSheet(QColor const & bgColor)
+// a style sheet for color frame widgets
+static inline QString colorFrameStyleSheet(QColor const & bgColor)
 {
        if (bgColor.isValid()) {
                QString rc = QLatin1String("background-color:");
@@ -167,7 +160,9 @@ bool is_backgroundcolor;
 lyx::RGBColor set_fontcolor;
 bool is_fontcolor;
 lyx::RGBColor set_notefontcolor;
+bool is_notefontcolor;
 lyx::RGBColor set_boxbgcolor;
+bool is_boxbgcolor;
 bool forced_fontspec_activation;
 
 } // anonymous namespace
@@ -177,7 +172,6 @@ namespace lyx {
 namespace {
 // used when sorting the textclass list.
 class less_textclass_avail_desc
-       : public binary_function<string, string, int>
 {
 public:
        bool operator()(string const & lhs, string const & rhs) const
@@ -269,15 +263,15 @@ class ModuleSelectionManager : public GuiSelectionManager
 public:
        ///
        ModuleSelectionManager(QObject * parent,
-                                                  QTreeView * availableLVarg,
-                                                  QTreeView * selectedLVarg,
-                                                  QPushButton * addPBarg,
-                                                  QPushButton * delPBarg,
-                                                  QPushButton * upPBarg,
-                                                  QPushButton * downPBarg,
-                                                  QStandardItemModel * availableModelarg,
-                                                  GuiIdListModel * selectedModelarg,
-                              GuiDocument const * container)
+                              QTreeView * availableLVarg,
+                              QTreeView * selectedLVarg,
+                              QPushButton * addPBarg,
+                              QPushButton * delPBarg,
+                              QPushButton * upPBarg,
+                              QPushButton * downPBarg,
+                              QStandardItemModel * availableModelarg,
+                              GuiIdListModel * selectedModelarg,
+                              GuiDocument const * container)
                : GuiSelectionManager(parent, availableLVarg, selectedLVarg, addPBarg, delPBarg,
                                                          upPBarg, downPBarg, availableModelarg, selectedModelarg),
                  container_(container)
@@ -290,13 +284,13 @@ public:
                        { excluded_modules_ = em.list(); }
 private:
        ///
-       virtual void updateAddPB();
+       void updateAddPB() override;
        ///
-       virtual void updateUpPB();
+       void updateUpPB() override;
        ///
-       virtual void updateDownPB();
+       void updateDownPB() override;
        ///
-       virtual void updateDelPB();
+       void updateDelPB() override;
        /// returns availableModel as a GuiIdListModel
        QStandardItemModel * getAvailableModel()
        {
@@ -329,6 +323,9 @@ void ModuleSelectionManager::updateAddPB()
        }
 
        QModelIndex const & idx = availableLV->selectionModel()->currentIndex();
+       
+       if (!idx.isValid())
+               return;
 
        if (getAvailableModel()->itemFromIndex(idx)->hasChildren()) {
                // This is a category header
@@ -358,7 +355,7 @@ void ModuleSelectionManager::updateDownPB()
                return;
        }
 
-       // determine whether immediately succeding element requires this one
+       // determine whether immediately succeeding element requires this one
        string const curmodname = getSelectedModel()->getIDString(curRow);
        string const nextmodname = getSelectedModel()->getIDString(curRow + 1);
 
@@ -477,28 +474,60 @@ void ModuleSelectionManager::updateDelPB()
 /////////////////////////////////////////////////////////////////////
 
 PreambleModule::PreambleModule(QWidget * parent)
-       : UiWidget<Ui::PreambleUi>(parent), current_id_(nullptr)
+       : UiWidget<Ui::PreambleUi>(parent), current_id_(nullptr),
+         highlighter_(new LaTeXHighlighter(preambleTE->document(), true))
 {
        // This is not a memory leak. The object will be destroyed
        // with this.
        // @ is letter in the LyX user preamble
-       (void) new LaTeXHighlighter(preambleTE->document(), true);
        preambleTE->setFont(guiApp->typewriterSystemFont());
        preambleTE->setWordWrapMode(QTextOption::NoWrap);
        setFocusProxy(preambleTE);
+       // Install event filter on find line edit to capture return/enter key
+       findLE->installEventFilter(this);
        connect(preambleTE, SIGNAL(textChanged()), this, SIGNAL(changed()));
        connect(findLE, SIGNAL(textEdited(const QString &)), this, SLOT(checkFindButton()));
        connect(findButtonPB, SIGNAL(clicked()), this, SLOT(findText()));
        connect(editPB, SIGNAL(clicked()), this, SLOT(editExternal()));
        connect(findLE, SIGNAL(returnPressed()), this, SLOT(findText()));
        checkFindButton();
-       // https://stackoverflow.com/questions/13027091/how-to-override-tab-width-in-qt
-       const int tabStop = 4;
+       int const tabStop = 4;
        QFontMetrics metrics(preambleTE->currentFont());
+#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
+       // horizontalAdvance() is available starting in 5.11.0
+       // setTabStopDistance() is available starting in 5.10.0
+       preambleTE->setTabStopDistance(tabStop * metrics.horizontalAdvance(' '));
+#else
        preambleTE->setTabStopWidth(tabStop * metrics.width(' '));
+#endif
+}
+
+
+bool PreambleModule::eventFilter(QObject * sender, QEvent * event)
+{
+       if (sender == findLE) {
+               if (event->type() == QEvent::KeyPress) {
+                       QKeyEvent * key = static_cast<QKeyEvent *>(event);
+                       if ((key->key() == Qt::Key_Enter) || (key->key() == Qt::Key_Return)) {
+                               findText();
+                               // Return true to filter out the event
+                               return true;
+                       }
+               }
+       }
+       if (event->type() == QEvent::ApplicationPaletteChange) {
+               // mode switch: colors need to be updated
+               // and the highlighting redone
+               if (highlighter_) {
+                       highlighter_->setupColors();
+                       highlighter_->rehighlight();
+               }
+       }
+       return QWidget::eventFilter(sender, event);
 }
 
 
+
 void PreambleModule::checkFindButton()
 {
        findButtonPB->setEnabled(!findLE->text().isEmpty());
@@ -574,7 +603,8 @@ void PreambleModule::editExternal() {
                docstring const s = tempfilename.fileContents("UTF-8");
                preambleTE->document()->setPlainText(toqstr(s));
                tempfile_.reset();
-               editPB->setText(qt_("&Edit"));
+               editPB->setText(qt_("&Edit Externally"));
+               editPB->setIcon(QIcon());
                changed();
                return;
        }
@@ -591,6 +621,9 @@ void PreambleModule::editExternal() {
        preambleTE->setReadOnly(true);
        theFormats().edit(*current_id_, tempfilename, format);
        editPB->setText(qt_("&End Edit"));
+       QIcon warn(guiApp ? guiApp->getScaledPixmap("images/", "emblem-shellescape-user")
+                         : getPixmap("images/", "emblem-shellescape", "svgz,png"));
+       editPB->setIcon(warn);
        changed();
 }
 
@@ -610,6 +643,15 @@ LocalLayout::LocalLayout(QWidget * parent)
        connect(validatePB, SIGNAL(clicked()), this, SLOT(validatePressed()));
        connect(convertPB, SIGNAL(clicked()), this, SLOT(convertPressed()));
        connect(editPB, SIGNAL(clicked()), this, SLOT(editExternal()));
+       int const tabStop = 4;
+       QFontMetrics metrics(locallayoutTE->currentFont());
+#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
+       // horizontalAdvance() is available starting in 5.11.0
+       // setTabStopDistance() is available starting in 5.10.0
+       locallayoutTE->setTabStopDistance(tabStop * metrics.horizontalAdvance(' '));
+#else
+       locallayoutTE->setTabStopWidth(tabStop * metrics.width(' '));
+#endif
 }
 
 
@@ -647,23 +689,18 @@ void LocalLayout::hideConvert()
 
 void LocalLayout::textChanged()
 {
-       // Flashy red bold text
-       static const QString ivpar("<p style=\"color: #c00000; font-weight: bold; text-align:left\">"
-                                  "%1</p>");
-       static const QString message = ivpar.arg(qt_("Validation required!"));
+       validLB->setText("");
        string const layout =
                fromqstr(locallayoutTE->document()->toPlainText().trimmed());
 
        if (layout.empty()) {
                validated_ = true;
                validatePB->setEnabled(false);
-               validLB->setText("");
                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);
                hideConvert();
                changed();
@@ -746,7 +783,8 @@ void LocalLayout::editExternal() {
                docstring const s = tempfilename.fileContents("UTF-8");
                locallayoutTE->document()->setPlainText(toqstr(s));
                tempfile_.reset();
-               editPB->setText(qt_("&Edit"));
+               editPB->setText(qt_("&Edit Externally"));
+               editPB->setIcon(QIcon());
                changed();
                return;
        }
@@ -763,6 +801,9 @@ void LocalLayout::editExternal() {
        locallayoutTE->setReadOnly(true);
        theFormats().edit(*current_id_, tempfilename, format);
        editPB->setText(qt_("&End Edit"));
+       QIcon warn(guiApp ? guiApp->getScaledPixmap("images/", "emblem-shellescape-user")
+                         : getPixmap("images/", "emblem-shellescape", "svgz,png"));
+       editPB->setIcon(warn);
        validatePB->setEnabled(false);
        hideConvert();
        changed();
@@ -778,7 +819,8 @@ void LocalLayout::editExternal() {
 GuiDocument::GuiDocument(GuiView & lv)
        : GuiDialog(lv, "document", qt_("Document Settings")),
          biblioChanged_(false), nonModuleChanged_(false),
-         modulesChanged_(false), shellescapeChanged_(false)
+         modulesChanged_(false), shellescapeChanged_(false),
+         switchback_(false), prompted_(false)
 {
        setupUi(this);
 
@@ -849,16 +891,18 @@ GuiDocument::GuiDocument(GuiView & lv)
        textLayoutModule->lspacingLE->setValidator(new QDoubleValidator(
                textLayoutModule->lspacingLE));
        textLayoutModule->indentLE->setValidator(new LengthValidator(
-               textLayoutModule->indentLE));
+               textLayoutModule->indentLE, false));
        textLayoutModule->skipLE->setValidator(new LengthValidator(
-               textLayoutModule->skipLE));
-
-       textLayoutModule->indentCO->addItem(qt_("Default"));
-       textLayoutModule->indentCO->addItem(qt_("Custom"));
-       textLayoutModule->skipCO->addItem(qt_("SmallSkip"));
-       textLayoutModule->skipCO->addItem(qt_("MedSkip"));
-       textLayoutModule->skipCO->addItem(qt_("BigSkip"));
-       textLayoutModule->skipCO->addItem(qt_("Custom"));
+               textLayoutModule->skipLE, false));
+
+       textLayoutModule->indentCO->addItem(qt_("Default"), toqstr("default"));
+       textLayoutModule->indentCO->addItem(qt_("Custom"), toqstr("custom"));
+       textLayoutModule->skipCO->addItem(qt_("Half line height"), VSpace::HALFLINE);
+       textLayoutModule->skipCO->addItem(qt_("Line height"), VSpace::FULLLINE);
+       textLayoutModule->skipCO->addItem(qt_("Small Skip"), VSpace::SMALLSKIP);
+       textLayoutModule->skipCO->addItem(qt_("Medium Skip"), VSpace::MEDSKIP);
+       textLayoutModule->skipCO->addItem(qt_("Big Skip"), VSpace::BIGSKIP);
+       textLayoutModule->skipCO->addItem(qt_("Custom"), VSpace::LENGTH);
        textLayoutModule->lspacingCO->insertItem(
                Spacing::Single, qt_("Single"));
        textLayoutModule->lspacingCO->insertItem(
@@ -868,8 +912,10 @@ GuiDocument::GuiDocument(GuiView & lv)
        textLayoutModule->lspacingCO->insertItem(
                Spacing::Other, qt_("Custom"));
        // initialize the length validator
-       bc().addCheckedLineEdit(textLayoutModule->indentLE);
-       bc().addCheckedLineEdit(textLayoutModule->skipLE);
+       bc().addCheckedLineEdit(textLayoutModule->indentLE, textLayoutModule->indentRB);
+       bc().addCheckedLineEditPanel(textLayoutModule->indentLE, docPS, N_("Text Layout"));
+       bc().addCheckedLineEdit(textLayoutModule->skipLE, textLayoutModule->skipRB);
+       bc().addCheckedLineEditPanel(textLayoutModule->skipLE, docPS, N_("Text Layout"));
 
        textLayoutModule->tableStyleCO->addItem(qt_("Default"), toqstr("default"));
        getTableStyles();
@@ -883,23 +929,22 @@ GuiDocument::GuiDocument(GuiView & lv)
        connect(masterChildModule->includeonlyRB, SIGNAL(toggled(bool)),
                masterChildModule->childrenTW, SLOT(setEnabled(bool)));
        connect(masterChildModule->includeonlyRB, SIGNAL(toggled(bool)),
-               masterChildModule->maintainAuxCB, SLOT(setEnabled(bool)));
+               masterChildModule->maintainGB, SLOT(setEnabled(bool)));
        connect(masterChildModule->includeallRB, SIGNAL(clicked()),
                this, SLOT(change_adaptor()));
        connect(masterChildModule->includeonlyRB, SIGNAL(clicked()),
                this, SLOT(change_adaptor()));
-       connect(masterChildModule->maintainAuxCB, SIGNAL(clicked()),
+       connect(masterChildModule->maintainCRNoneRB, SIGNAL(clicked()),
+               this, SLOT(change_adaptor()));
+       connect(masterChildModule->maintainCRMostlyRB, SIGNAL(clicked()),
+               this, SLOT(change_adaptor()));
+       connect(masterChildModule->maintainCRStrictRB, SIGNAL(clicked()),
                this, SLOT(change_adaptor()));
        masterChildModule->childrenTW->setColumnCount(2);
        masterChildModule->childrenTW->headerItem()->setText(0, qt_("Child Document"));
        masterChildModule->childrenTW->headerItem()->setText(1, qt_("Include to Output"));
-#if (QT_VERSION > 0x050000)
-        masterChildModule->childrenTW->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
-        masterChildModule->childrenTW->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
-#else
-        masterChildModule->childrenTW->header()->setResizeMode(0, QHeaderView::ResizeToContents);
-        masterChildModule->childrenTW->header()->setResizeMode(1, QHeaderView::ResizeToContents);
-#endif
+       masterChildModule->childrenTW->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
+       masterChildModule->childrenTW->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
 
        // Formats
        outputModule = new UiWidget<Ui::OutputUi>(this);
@@ -914,6 +959,10 @@ GuiDocument::GuiDocument(GuiView & lv)
                this, SLOT(change_adaptor()));
        connect(outputModule->mathoutCB, SIGNAL(currentIndexChanged(int)),
                this, SLOT(change_adaptor()));
+       connect(outputModule->tableoutCB, SIGNAL(currentIndexChanged(int)),
+               this, SLOT(change_adaptor()));
+       connect(outputModule->mathmlprefixCB, SIGNAL(currentIndexChanged(int)),
+               this, SLOT(change_adaptor()));
 
        connect(outputModule->shellescapeCB, SIGNAL(stateChanged(int)),
                this, SLOT(shellescapeChanged()));
@@ -926,7 +975,7 @@ GuiDocument::GuiDocument(GuiView & lv)
        outputModule->synccustomCB->addItem("\\synctex=-1");
        outputModule->synccustomCB->addItem("\\usepackage[active]{srcltx}");
 
-       outputModule->synccustomCB->setValidator(new NoNewLineValidator(
+       outputModule->synccustomCB->lineEdit()->setValidator(new NoNewLineValidator(
                outputModule->synccustomCB));
 
        connect(outputModule->saveTransientPropertiesCB, SIGNAL(clicked()),
@@ -936,7 +985,7 @@ GuiDocument::GuiDocument(GuiView & lv)
 
 
        // language & quote
-       // this must preceed font, since fonts depend on this
+       // this must precede font, since fonts depend on this
        langModule = new UiWidget<Ui::LanguageUi>(this);
        connect(langModule->languageCO, SIGNAL(activated(int)),
                this, SLOT(change_adaptor()));
@@ -1017,7 +1066,7 @@ GuiDocument::GuiDocument(GuiView & lv)
                if (encvar.unsafe() ||encvar.guiName().empty()
                    || utf8_base_encodings.contains(toqstr(encvar.name())))
                        continue;
-               if (std::string(encvar.name()).find("utf8") == 0)
+               if (encvar.name().find("utf8") == 0)
                        encodingmap_utf8.insert(qt_(encvar.guiName()), toqstr(encvar.name()));
                else
                        encodingmap.insert(qt_(encvar.guiName()), toqstr(encvar.name()));
@@ -1125,7 +1174,7 @@ GuiDocument::GuiDocument(GuiView & lv)
        fontModule->fontsizeCO->addItem(qt_("11"));
        fontModule->fontsizeCO->addItem(qt_("12"));
 
-       fontModule->fontencCO->addItem(qt_("Automatic"), QString("auto"));
+       fontModule->fontencCO->addItem(qt_("Automatic[[encoding]]"), QString("auto"));
        fontModule->fontencCO->addItem(qt_("Class Default"), QString("default"));
        fontModule->fontencCO->addItem(qt_("Custom"), QString("custom"));
 
@@ -1173,8 +1222,10 @@ GuiDocument::GuiDocument(GuiView & lv)
        pageLayoutModule->pagestyleCO->addItem(qt_("fancy"));
        bc().addCheckedLineEdit(pageLayoutModule->paperheightLE,
                pageLayoutModule->paperheightL);
+       bc().addCheckedLineEditPanel(pageLayoutModule->paperheightLE, docPS, N_("Page Layout"));
        bc().addCheckedLineEdit(pageLayoutModule->paperwidthLE,
                pageLayoutModule->paperwidthL);
+       bc().addCheckedLineEditPanel(pageLayoutModule->paperwidthLE, docPS, N_("Page Layout"));
 
        QComboBox * cb = pageLayoutModule->papersizeCO;
        cb->addItem(qt_("Default"));
@@ -1221,7 +1272,7 @@ GuiDocument::GuiDocument(GuiView & lv)
 
        // margins
        marginsModule = new UiWidget<Ui::MarginsUi>(this);
-       connect(marginsModule->marginCB, SIGNAL(toggled(bool)),
+       connect(marginsModule->marginCB, SIGNAL(clicked(bool)),
                this, SLOT(setCustomMargins(bool)));
        connect(marginsModule->marginCB, SIGNAL(clicked()),
                this, SLOT(change_adaptor()));
@@ -1276,20 +1327,36 @@ GuiDocument::GuiDocument(GuiView & lv)
 
        bc().addCheckedLineEdit(marginsModule->topLE,
                marginsModule->topL);
+       bc().addCheckedLineEditPanel(marginsModule->topLE,
+                                    docPS, N_("Page Margins"));
        bc().addCheckedLineEdit(marginsModule->bottomLE,
                marginsModule->bottomL);
+       bc().addCheckedLineEditPanel(marginsModule->bottomLE,
+                                    docPS, N_("Page Margins"));
        bc().addCheckedLineEdit(marginsModule->innerLE,
                marginsModule->innerL);
+       bc().addCheckedLineEditPanel(marginsModule->innerLE,
+                                    docPS, N_("Page Margins"));
        bc().addCheckedLineEdit(marginsModule->outerLE,
                marginsModule->outerL);
+       bc().addCheckedLineEditPanel(marginsModule->outerLE,
+                                    docPS, N_("Page Margins"));
        bc().addCheckedLineEdit(marginsModule->headsepLE,
                marginsModule->headsepL);
+       bc().addCheckedLineEditPanel(marginsModule->headsepLE,
+                                    docPS, N_("Page Margins"));
        bc().addCheckedLineEdit(marginsModule->headheightLE,
                marginsModule->headheightL);
+       bc().addCheckedLineEditPanel(marginsModule->headheightLE,
+                                    docPS, N_("Page Margins"));
        bc().addCheckedLineEdit(marginsModule->footskipLE,
                marginsModule->footskipL);
+       bc().addCheckedLineEditPanel(marginsModule->footskipLE,
+                                    docPS, N_("Page Margins"));
        bc().addCheckedLineEdit(marginsModule->columnsepLE,
                marginsModule->columnsepL);
+       bc().addCheckedLineEditPanel(marginsModule->columnsepLE,
+                                    docPS, N_("Page Margins"));
 
 
        // color
@@ -1311,6 +1378,7 @@ GuiDocument::GuiDocument(GuiView & lv)
        connect(colorModule->delBoxBackgroundTB, SIGNAL(clicked()),
                this, SLOT(deleteBoxBackgroundColor()));
 
+
        // change tracking
        changesModule = new UiWidget<Ui::ChangeTrackingUi>(this);
        connect(changesModule->trackChangesCB, SIGNAL(clicked()),
@@ -1319,6 +1387,9 @@ GuiDocument::GuiDocument(GuiView & lv)
                this, SLOT(outputChangesToggled(bool)));
        connect(changesModule->changeBarsCB, SIGNAL(clicked()),
                this, SLOT(change_adaptor()));
+       connect(&lv, SIGNAL(changeTrackingToggled(bool)),
+               this, SLOT(changeTrackingChanged(bool)));
+
 
        // numbering
        numberingModule = new UiWidget<Ui::NumberingUi>(this);
@@ -1334,7 +1405,7 @@ GuiDocument::GuiDocument(GuiView & lv)
        numberingModule->tocTW->headerItem()->setText(0, qt_("Example"));
        numberingModule->tocTW->headerItem()->setText(1, qt_("Numbered"));
        numberingModule->tocTW->headerItem()->setText(2, qt_("Appears in TOC"));
-       setSectionResizeMode(numberingModule->tocTW->header(), QHeaderView::ResizeToContents);
+       numberingModule->tocTW->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
        connect(numberingModule->linenoCB, SIGNAL(toggled(bool)),
                this, SLOT(linenoToggled(bool)));
        connect(numberingModule->linenoCB, SIGNAL(clicked()),
@@ -1424,7 +1495,7 @@ GuiDocument::GuiDocument(GuiView & lv)
        headers << qt_("Package") << qt_("Load automatically")
                << qt_("Load always") << qt_("Do not load");
        mathsModule->packagesTW->setHorizontalHeaderLabels(headers);
-       setSectionResizeMode(mathsModule->packagesTW->horizontalHeader(), QHeaderView::Stretch);
+       mathsModule->packagesTW->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
        map<string, string> const & packages = BufferParams::auto_packages();
        mathsModule->packagesTW->setRowCount(packages.size());
        int packnum = 0;
@@ -1509,26 +1580,27 @@ GuiDocument::GuiDocument(GuiView & lv)
        connect(mathsModule->MathNumberingPosCO, SIGNAL(activated(int)),
                this, SLOT(change_adaptor()));
 
-       connect(mathsModule->MathIndentCB, SIGNAL(toggled(bool)),
-               this, SLOT(change_adaptor()));
        connect(mathsModule->MathIndentCB, SIGNAL(toggled(bool)),
                this, SLOT(allowMathIndent()));
-       connect(mathsModule->MathIndentCO, SIGNAL(activated(int)),
+       connect(mathsModule->MathIndentCB, SIGNAL(toggled(bool)),
                this, SLOT(change_adaptor()));
        connect(mathsModule->MathIndentCO, SIGNAL(activated(int)),
                this, SLOT(enableMathIndent(int)));
+       connect(mathsModule->MathIndentCO, SIGNAL(activated(int)),
+               this, SLOT(change_adaptor()));
        connect(mathsModule->MathIndentLE, SIGNAL(textChanged(const QString &)),
                this, SLOT(change_adaptor()));
        connect(mathsModule->MathIndentLengthCO, SIGNAL(activated(int)),
                this, SLOT(change_adaptor()));
 
 
-       mathsModule->MathIndentCO->addItem(qt_("Default"));
-       mathsModule->MathIndentCO->addItem(qt_("Custom"));
+       mathsModule->MathIndentCO->addItem(qt_("Default"), toqstr("default"));
+       mathsModule->MathIndentCO->addItem(qt_("Custom"), toqstr("custom"));
        mathsModule->MathIndentLE->setValidator(new LengthValidator(
-               mathsModule->MathIndentLE));
+               mathsModule->MathIndentLE, false));
        // initialize the length validator
-       bc().addCheckedLineEdit(mathsModule->MathIndentLE);
+       bc().addCheckedLineEdit(mathsModule->MathIndentLE, mathsModule->MathIndentCB);
+       bc().addCheckedLineEditPanel(mathsModule->MathIndentLE, docPS, N_("Math Options"));
        mathsModule->MathNumberingPosCO->addItem(qt_("Left"));
        mathsModule->MathNumberingPosCO->addItem(qt_("Default"));
        mathsModule->MathNumberingPosCO->addItem(qt_("Right"));
@@ -1561,6 +1633,8 @@ GuiDocument::GuiDocument(GuiView & lv)
                this, SLOT(change_adaptor()));
        connect(latexModule->refstyleCB, SIGNAL(clicked()),
                this, SLOT(change_adaptor()));
+       connect(latexModule->refFormattedCB, SIGNAL(clicked()),
+               this, SLOT(change_adaptor()));
 
        latexModule->optionsLE->setValidator(new NoNewLineValidator(
                latexModule->optionsLE));
@@ -1584,7 +1658,7 @@ GuiDocument::GuiDocument(GuiView & lv)
                // tooltip sensu "KOMA-Script Article [Class 'scrartcl']"
                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");
+                       docstring const output_type = _("LaTeX");
                        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."),
@@ -1627,10 +1701,10 @@ GuiDocument::GuiDocument(GuiView & lv)
        // Modules
        modulesModule = new UiWidget<Ui::ModulesUi>(this);
        modulesModule->availableLV->header()->setVisible(false);
-       setSectionResizeMode(modulesModule->availableLV->header(), QHeaderView::ResizeToContents);
+       modulesModule->availableLV->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
        modulesModule->availableLV->header()->setStretchLastSection(false);
        modulesModule->selectedLV->header()->setVisible(false);
-       setSectionResizeMode(modulesModule->selectedLV->header(), QHeaderView::ResizeToContents);
+       modulesModule->selectedLV->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
        modulesModule->selectedLV->header()->setStretchLastSection(false);
        selectionManager =
                new ModuleSelectionManager(this, modulesModule->availableLV,
@@ -1646,10 +1720,7 @@ GuiDocument::GuiDocument(GuiView & lv)
                this, SLOT(modulesChanged()));
        // The filter bar
        filter_ = new FancyLineEdit(this);
-       filter_->setButtonPixmap(FancyLineEdit::Right, getPixmap("images/", "editclear", "svgz,png"));
-       filter_->setButtonVisible(FancyLineEdit::Right, true);
-       filter_->setButtonToolTip(FancyLineEdit::Right, qt_("Clear text"));
-       filter_->setAutoHideButton(FancyLineEdit::Right, true);
+       filter_->setClearButton(true);
        filter_->setPlaceholderText(qt_("All avail. modules"));
        modulesModule->moduleFilterBarL->addWidget(filter_, 0);
        modulesModule->findModulesLA->setBuddy(filter_);
@@ -1660,13 +1731,8 @@ GuiDocument::GuiDocument(GuiView & lv)
                this, SLOT(moduleFilterChanged(QString)));
        connect(filter_, SIGNAL(returnPressed()),
                this, SLOT(moduleFilterPressed()));
-#if (QT_VERSION < 0x050000)
-       connect(filter_, SIGNAL(downPressed()),
-               modulesModule->availableLV, SLOT(setFocus()));
-#else
        connect(filter_, &FancyLineEdit::downPressed,
-               modulesModule->availableLV, [=](){ focusAndHighlight(modulesModule->availableLV); });
-#endif
+               modulesModule->availableLV, [this](){ focusAndHighlight(modulesModule->availableLV); });
 
 
        // PDF support
@@ -1687,6 +1753,8 @@ GuiDocument::GuiDocument(GuiView & lv)
                this, SLOT(change_adaptor()));
        connect(pdfSupportModule->bookmarksopenGB, SIGNAL(toggled(bool)),
                this, SLOT(change_adaptor()));
+       connect(pdfSupportModule->bookmarksopenGB, SIGNAL(toggled(bool)),
+               this, SLOT(bookmarksopenChanged(bool)));
        connect(pdfSupportModule->bookmarksopenlevelSB, SIGNAL(valueChanged(int)),
                this, SLOT(change_adaptor()));
        connect(pdfSupportModule->breaklinksCB, SIGNAL(toggled(bool)),
@@ -1701,7 +1769,9 @@ GuiDocument::GuiDocument(GuiView & lv)
                this, SLOT(change_adaptor()));
        connect(pdfSupportModule->fullscreenCB, SIGNAL(toggled(bool)),
                this, SLOT(change_adaptor()));
-       connect(pdfSupportModule->optionsLE, SIGNAL(textChanged(QString)),
+       connect(pdfSupportModule->optionsTE, SIGNAL(textChanged()),
+               this, SLOT(change_adaptor()));
+       connect(pdfSupportModule->metadataTE, SIGNAL(textChanged()),
                this, SLOT(change_adaptor()));
 
        pdfSupportModule->titleLE->setValidator(new NoNewLineValidator(
@@ -1712,8 +1782,11 @@ GuiDocument::GuiDocument(GuiView & lv)
                pdfSupportModule->subjectLE));
        pdfSupportModule->keywordsLE->setValidator(new NoNewLineValidator(
                pdfSupportModule->keywordsLE));
-       pdfSupportModule->optionsLE->setValidator(new NoNewLineValidator(
-               pdfSupportModule->optionsLE));
+
+       pdf_options_highlighter_ = new LaTeXHighlighter(
+                               pdfSupportModule->optionsTE->document(), true, true);
+       pdf_metadata_highlighter_ = new LaTeXHighlighter(
+                               pdfSupportModule->metadataTE->document(), true, true);
 
        for (int i = 0; backref_opts[i][0]; ++i)
                pdfSupportModule->backrefCO->addItem(qt_(backref_opts_gui[i]));
@@ -1743,7 +1816,7 @@ GuiDocument::GuiDocument(GuiView & lv)
                qt_("Input listings parameters below. Enter ? for a list of parameters."));
 
        for (int i = 0; lst_packages[i][0]; ++i)
-            listingsModule->packageCO->addItem(lst_packages[i]);
+               listingsModule->packageCO->addItem(lst_packages[i]);
 
 
        // add the panels
@@ -1767,19 +1840,50 @@ GuiDocument::GuiDocument(GuiView & lv)
        docPS->addPanel(listingsModule, N_("Listings[[inset]]"));
        docPS->addPanel(bulletsModule, N_("Bullets"));
        docPS->addPanel(branchesModule, N_("Branches"));
-       docPS->addPanel(outputModule, N_("Formats[[output]]"));
+       docPS->addPanel(outputModule, N_("Output"));
        docPS->addPanel(preambleModule, N_("LaTeX Preamble"));
        docPS->setCurrentPanel("Document Class");
-// FIXME: hack to work around resizing bug in Qt >= 4.2
-// bug verified with Qt 4.2.{0-3} (JSpitzm)
-#if QT_VERSION >= 0x040200
-       docPS->updateGeometry();
-#endif
+
+       // Filter out (dark/light) mode changes
+       installEventFilter(this);
 }
 
 
 void GuiDocument::onBufferViewChanged()
 {
+       if (switchback_) {
+               // We are just switching back. Nothing to do.
+               switchback_ = false;
+               return;
+       }
+       BufferView const * view = bufferview();
+       string const new_filename = view ? view->buffer().absFileName() : string();
+       // If we switched buffer really and the previous file name is different to
+       // the current one, we ask on unapplied changes (#9369)
+       // FIXME: This is more complicated than it should be. Why do we need these to cycles?
+       // And ideally, we should propose to apply without having to switch back
+       // (e.g., via a LFUN_BUFFER_PARAMS_APPLY_OTHER)
+       if (!prev_buffer_filename_.empty() && prev_buffer_filename_ != new_filename
+           && buttonBox->button(QDialogButtonBox::Apply)->isEnabled()) {
+               // Only ask if we haven't yet in this cycle
+               int const ret = prompted_ ? 3 : Alert::prompt(_("Unapplied changes"),
+                               _("Some changes in the previous document were not yet applied.\n"
+                               "Do you want to switch back and apply them?"),
+                               1, 1, _("Yes, &Switch Back"), _("No, &Dismiss Changes"));
+               if (ret == 0) {
+                       // Switch to previous buffer view and apply
+                       switchback_ = true;
+                       // Record that we have asked.
+                       prompted_ = true;
+                       lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH, prev_buffer_filename_));
+                       return;
+               } else if (ret == 3) {
+                       // We are in the second cycle. Set back.
+                       prompted_ = false;
+                       return;
+               }
+       }
+
        if (isVisibleView())
                initialiseParams("");
 }
@@ -1810,6 +1914,20 @@ void GuiDocument::shellescapeChanged()
        changed();
 }
 
+void GuiDocument::bookmarksopenChanged(bool state)
+{
+       pdfSupportModule->bookmarksopenlevelSB->setEnabled(state);
+       pdfSupportModule->bookmarksopenlevelLA->setEnabled(state);
+}
+
+
+void GuiDocument::changeTrackingChanged(bool state)
+{
+       // This is triggered if the CT state is toggled outside
+       // the document dialog (e.g., menu).
+       changesModule->trackChangesCB->setChecked(state);
+}
+
 
 void GuiDocument::slotApply()
 {
@@ -1819,6 +1937,7 @@ void GuiDocument::slotApply()
        if (wasclean && only_shellescape_changed)
                buffer().markClean();
        modulesChanged_ = false;
+       isValid();
 }
 
 
@@ -1868,8 +1987,10 @@ void GuiDocument::filterModules(QString const & str)
                        return 0 < b.name.localeAwareCompare(a.name);
                });
 
-       QIcon user_icon(getPixmap("images/", "lyxfiles-user", "svgz,png"));
-       QIcon system_icon(getPixmap("images/", "lyxfiles-system", "svgz,png"));
+       QIcon user_icon(guiApp ? guiApp->getScaledPixmap("images/", "lyxfiles-user")
+                              : getPixmap("images/", "lyxfiles-user", "svgz,png"));
+       QIcon system_icon(guiApp ? guiApp->getScaledPixmap("images/", "lyxfiles-system")
+                                : getPixmap("images/", "lyxfiles-system", "svgz,png"));
 
        int i = 0;
        for (modInfoStruct const & m : modInfoList) {
@@ -1878,6 +1999,7 @@ void GuiDocument::filterModules(QString const & str)
                        item->setData(m.name, Qt::DisplayRole);
                        item->setData(toqstr(m.id), Qt::UserRole);
                        item->setData(m.description, Qt::ToolTipRole);
+                       item->setEditable(false);
                        if (m.local)
                                item->setIcon(user_icon);
                        else
@@ -1919,16 +2041,16 @@ void GuiDocument::includeonlyClicked(QTreeWidgetItem * item, int)
                return;
 
        string child = fromqstr(item->text(0));
+
        if (child.empty())
                return;
 
-       if (std::find(includeonlys_.begin(),
-                     includeonlys_.end(), child) != includeonlys_.end())
+       if (isChildIncluded(child))
                includeonlys_.remove(child);
        else
                includeonlys_.push_back(child);
 
-       updateIncludeonlys();
+       updateIncludeonlys(false);
        change_adaptor();
 }
 
@@ -1952,16 +2074,16 @@ void GuiDocument::setListingsMessage()
        static bool isOK = true;
        QString msg = validateListingsParameters();
        if (msg.isEmpty()) {
+               listingsModule->listingsTB->setTextColor(QColor());
                if (isOK)
                        return;
                isOK = true;
-               // listingsTB->setTextColor("black");
                listingsModule->listingsTB->setPlainText(
                        qt_("Input listings parameters below. "
                            "Enter ? for a list of parameters."));
        } else {
                isOK = false;
-               // listingsTB->setTextColor("red");
+               listingsModule->listingsTB->setTextColor(QColor(255, 0, 0));
                listingsModule->listingsTB->setPlainText(msg);
        }
 }
@@ -1969,17 +2091,17 @@ void GuiDocument::setListingsMessage()
 
 void GuiDocument::listingsPackageChanged(int index)
 {
-        string const package = lst_packages[index];
-        if (package == "Minted" && lyxrc.pygmentize_command.empty()) {
-                Alert::warning(_("Pygments driver command not found!"),
-                    _("The driver command necessary to use the minted package\n"
-                      "(pygmentize) has not been found. Make sure you have\n"
-                      "the python-pygments module installed or, if the driver\n"
-                      "is named differently, to add the following line to the\n"
-                      "document preamble:\n\n"
-                      "\\AtBeginDocument{\\renewcommand{\\MintedPygmentize}{driver}}\n\n"
-                      "where 'driver' is name of the driver command."));
-        }
+       string const package = lst_packages[index];
+       if (package == "Minted" && lyxrc.pygmentize_command.empty()) {
+               Alert::warning(_("Pygments driver command not found!"),
+                   _("The driver command necessary to use the minted package\n"
+                     "(pygmentize) has not been found. Make sure you have\n"
+                     "the python-pygments module installed or, if the driver\n"
+                     "is named differently, to add the following line to the\n"
+                     "document preamble:\n\n"
+                     "\\AtBeginDocument{\\renewcommand{\\MintedPygmentize}{driver}}\n\n"
+                     "where 'driver' is name of the driver command."));
+       }
 }
 
 
@@ -1991,11 +2113,13 @@ void GuiDocument::setLSpacing(int item)
 
 void GuiDocument::setIndent(int item)
 {
-       bool const enable = (item == 1);
+       bool const enable = (textLayoutModule->indentCO->itemData(item) == "custom");
        textLayoutModule->indentLE->setEnabled(enable);
        textLayoutModule->indentLengthCO->setEnabled(enable);
        textLayoutModule->skipLE->setEnabled(false);
        textLayoutModule->skipLengthCO->setEnabled(false);
+       // needed to catch empty custom case
+       bc().refresh();
        isValid();
 }
 
@@ -2011,9 +2135,13 @@ void GuiDocument::enableIndent(bool indent)
 
 void GuiDocument::setSkip(int item)
 {
-       bool const enable = (item == 3);
+       VSpace::VSpaceKind kind =
+               VSpace::VSpaceKind(textLayoutModule->skipCO->itemData(item).toInt());
+       bool const enable = (kind == VSpace::LENGTH);
        textLayoutModule->skipLE->setEnabled(enable);
        textLayoutModule->skipLengthCO->setEnabled(enable);
+       // needed to catch empty custom case
+       bc().refresh();
        isValid();
 }
 
@@ -2033,7 +2161,7 @@ void GuiDocument::allowMathIndent() {
                mathsModule->MathIndentLengthCO->setEnabled(false);
        }
        if (mathsModule->MathIndentCB->isChecked()
-           && mathsModule->MathIndentCO->currentIndex() == 1) {
+           && mathsModule->MathIndentCO->itemData(mathsModule->MathIndentCO->currentIndex()) == "custom") {
                        mathsModule->MathIndentLE->setEnabled(true);
                        mathsModule->MathIndentLengthCO->setEnabled(true);
        }
@@ -2045,6 +2173,8 @@ void GuiDocument::enableMathIndent(int item)
        bool const enable = (item == 1);
        mathsModule->MathIndentLE->setEnabled(enable);
        mathsModule->MathIndentLengthCO->setEnabled(enable);
+       // needed to catch empty custom case
+       bc().refresh();
        isValid();
 }
 
@@ -2088,54 +2218,134 @@ void GuiDocument::setColSep()
 }
 
 
-void GuiDocument::setCustomMargins(bool custom)
-{
-       marginsModule->topL->setEnabled(!custom);
-       marginsModule->topLE->setEnabled(!custom);
-       marginsModule->topUnit->setEnabled(!custom);
+void GuiDocument::setCustomMargins(bool cb_checked)
+{
+       bool const custom_margins = !cb_checked;
+       if (custom_margins) {
+               Length::UNIT const default_unit = Length::defaultUnit();
+               // fill with chached values
+               lengthToWidgets(marginsModule->topLE,
+                               marginsModule->topUnit,
+                               tmp_topmargin_, default_unit);
+               lengthToWidgets(marginsModule->bottomLE,
+                               marginsModule->bottomUnit,
+                               tmp_bottommargin_, default_unit);
+               lengthToWidgets(marginsModule->innerLE,
+                               marginsModule->innerUnit,
+                               tmp_leftmargin_, default_unit);
+               lengthToWidgets(marginsModule->outerLE,
+                               marginsModule->outerUnit,
+                               tmp_rightmargin_, default_unit);
+               lengthToWidgets(marginsModule->headheightLE,
+                               marginsModule->headheightUnit,
+                               tmp_headheight_, default_unit);
+               lengthToWidgets(marginsModule->headsepLE,
+                               marginsModule->headsepUnit,
+                               tmp_headsep_, default_unit);
+               lengthToWidgets(marginsModule->footskipLE,
+                               marginsModule->footskipUnit,
+                               tmp_footskip_, default_unit);
+               lengthToWidgets(marginsModule->columnsepLE,
+                               marginsModule->columnsepUnit,
+                               tmp_columnsep_, default_unit);
+       } else { // default margins
+               // Cache current values
+               tmp_leftmargin_ = widgetsToLength(marginsModule->innerLE,
+                                                 marginsModule->innerUnit);
+               tmp_topmargin_ = widgetsToLength(marginsModule->topLE,
+                                                marginsModule->topUnit);
+               tmp_rightmargin_ = widgetsToLength(marginsModule->outerLE,
+                                                  marginsModule->outerUnit);
+               tmp_bottommargin_ = widgetsToLength(marginsModule->bottomLE,
+                                                   marginsModule->bottomUnit);
+               tmp_headheight_ = widgetsToLength(marginsModule->headheightLE,
+                                                 marginsModule->headheightUnit);
+               tmp_headsep_ = widgetsToLength(marginsModule->headsepLE,
+                                              marginsModule->headsepUnit);
+               tmp_footskip_ = widgetsToLength(marginsModule->footskipLE,
+                                               marginsModule->footskipUnit);
+               tmp_columnsep_ = widgetsToLength(marginsModule->columnsepLE,
+                                                marginsModule->columnsepUnit);
+               // clear widgets
+               marginsModule->topLE->clear();
+               marginsModule->bottomLE->clear();
+               marginsModule->innerLE->clear();
+               marginsModule->outerLE->clear();
+               marginsModule->headheightLE->clear();
+               marginsModule->headsepLE->clear();
+               marginsModule->footskipLE->clear();
+               marginsModule->columnsepLE->clear();
+       }
+
+       marginsModule->topL->setEnabled(custom_margins);
+       marginsModule->topLE->setEnabled(custom_margins);
+       marginsModule->topUnit->setEnabled(custom_margins);
 
-       marginsModule->bottomL->setEnabled(!custom);
-       marginsModule->bottomLE->setEnabled(!custom);
-       marginsModule->bottomUnit->setEnabled(!custom);
+       marginsModule->bottomL->setEnabled(custom_margins);
+       marginsModule->bottomLE->setEnabled(custom_margins);
+       marginsModule->bottomUnit->setEnabled(custom_margins);
 
-       marginsModule->innerL->setEnabled(!custom);
-       marginsModule->innerLE->setEnabled(!custom);
-       marginsModule->innerUnit->setEnabled(!custom);
+       marginsModule->innerL->setEnabled(custom_margins);
+       marginsModule->innerLE->setEnabled(custom_margins);
+       marginsModule->innerUnit->setEnabled(custom_margins);
 
-       marginsModule->outerL->setEnabled(!custom);
-       marginsModule->outerLE->setEnabled(!custom);
-       marginsModule->outerUnit->setEnabled(!custom);
+       marginsModule->outerL->setEnabled(custom_margins);
+       marginsModule->outerLE->setEnabled(custom_margins);
+       marginsModule->outerUnit->setEnabled(custom_margins);
 
-       marginsModule->headheightL->setEnabled(!custom);
-       marginsModule->headheightLE->setEnabled(!custom);
-       marginsModule->headheightUnit->setEnabled(!custom);
+       marginsModule->headheightL->setEnabled(custom_margins);
+       marginsModule->headheightLE->setEnabled(custom_margins);
+       marginsModule->headheightUnit->setEnabled(custom_margins);
 
-       marginsModule->headsepL->setEnabled(!custom);
-       marginsModule->headsepLE->setEnabled(!custom);
-       marginsModule->headsepUnit->setEnabled(!custom);
+       marginsModule->headsepL->setEnabled(custom_margins);
+       marginsModule->headsepLE->setEnabled(custom_margins);
+       marginsModule->headsepUnit->setEnabled(custom_margins);
 
-       marginsModule->footskipL->setEnabled(!custom);
-       marginsModule->footskipLE->setEnabled(!custom);
-       marginsModule->footskipUnit->setEnabled(!custom);
+       marginsModule->footskipL->setEnabled(custom_margins);
+       marginsModule->footskipLE->setEnabled(custom_margins);
+       marginsModule->footskipUnit->setEnabled(custom_margins);
 
-       bool const enableColSep = !custom &&
-                       textLayoutModule->twoColumnCB->checkState() == Qt::Checked;
+       bool const enableColSep = custom_margins &&
+                       textLayoutModule->twoColumnCB->isChecked();
        marginsModule->columnsepL->setEnabled(enableColSep);
        marginsModule->columnsepLE->setEnabled(enableColSep);
        marginsModule->columnsepUnit->setEnabled(enableColSep);
+
+       // set some placeholder text that hint on defaults
+       QString const placeholder = marginsModule->marginCB->isChecked() ?
+               qt_("Default margins") : qt_("Package defaults");
+       // set tooltip depending on gemoetry state
+       QString const tooltip = marginsModule->marginCB->isChecked() ?
+               qt_("If no value is given, the defaults as set by the class, a package or the preamble are used.")
+               : qt_("If no value is given, the defaults as set by the geometry package or a package/class overriding geometry's defaults are used.");
+       marginsModule->topLE->setPlaceholderText(placeholder);
+       marginsModule->bottomLE->setPlaceholderText(placeholder);
+       marginsModule->innerLE->setPlaceholderText(placeholder);
+       marginsModule->outerLE->setPlaceholderText(placeholder);
+       marginsModule->headheightLE->setPlaceholderText(placeholder);
+       marginsModule->headsepLE->setPlaceholderText(placeholder);
+       marginsModule->footskipLE->setPlaceholderText(placeholder);
+       marginsModule->columnsepLE->setPlaceholderText(placeholder);
+       marginsModule->topLE->setToolTip(tooltip);
+       marginsModule->bottomLE->setToolTip(tooltip);
+       marginsModule->innerLE->setToolTip(tooltip);
+       marginsModule->outerLE->setToolTip(tooltip);
+       marginsModule->headheightLE->setToolTip(tooltip);
+       marginsModule->headsepLE->setToolTip(tooltip);
+       marginsModule->footskipLE->setToolTip(tooltip);
+       marginsModule->columnsepLE->setToolTip(tooltip);
 }
 
 
 void GuiDocument::changeBackgroundColor()
 {
-       QColor const & newColor = QColorDialog::getColor(
-               rgb2qcolor(set_backgroundcolor), asQWidget());
+       QColor const & newColor = getColor(rgb2qcolor(set_backgroundcolor));
        if (!newColor.isValid())
                return;
-       // set the button color and text
-       colorModule->backgroundPB->setStyleSheet(
-               colorButtonStyleSheet(newColor));
-       colorModule->backgroundPB->setText(qt_("&Change..."));
+       // set the color
+       colorModule->pageBackgroundCF->setVisible(true);
+       colorModule->pageBackgroundCF->setStyleSheet(
+               colorFrameStyleSheet(newColor));
        // save color
        set_backgroundcolor = rgbFromHexName(fromqstr(newColor.name()));
        is_backgroundcolor = true;
@@ -2145,10 +2355,9 @@ void GuiDocument::changeBackgroundColor()
 
 void GuiDocument::deleteBackgroundColor()
 {
-       // set the button color back to default by setting an empty StyleSheet
-       colorModule->backgroundPB->setStyleSheet(QLatin1String(""));
-       // change button text
-       colorModule->backgroundPB->setText(qt_("&Default..."));
+       // set the color back to default by setting an empty StyleSheet
+       colorModule->pageBackgroundCF->setStyleSheet(QLatin1String(""));
+       colorModule->pageBackgroundCF->setVisible(false);
        // save default color (white)
        set_backgroundcolor = rgbFromHexName("#ffffff");
        is_backgroundcolor = false;
@@ -2158,14 +2367,13 @@ void GuiDocument::deleteBackgroundColor()
 
 void GuiDocument::changeFontColor()
 {
-       QColor const & newColor = QColorDialog::getColor(
-               rgb2qcolor(set_fontcolor), asQWidget());
+       QColor const & newColor = getColor(rgb2qcolor(set_fontcolor));
        if (!newColor.isValid())
                return;
-       // set the button color and text
-       colorModule->fontColorPB->setStyleSheet(
-               colorButtonStyleSheet(newColor));
-       colorModule->fontColorPB->setText(qt_("&Change..."));
+       //  set the color
+       colorModule->mainTextCF->setVisible(true);
+       colorModule->mainTextCF->setStyleSheet(
+               colorFrameStyleSheet(newColor));
        // save color
        set_fontcolor = rgbFromHexName(fromqstr(newColor.name()));
        is_fontcolor = true;
@@ -2176,9 +2384,8 @@ void GuiDocument::changeFontColor()
 void GuiDocument::deleteFontColor()
 {
        // set the button color back to default by setting an empty StyleSheet
-       colorModule->fontColorPB->setStyleSheet(QLatin1String(""));
-       // change button text
-       colorModule->fontColorPB->setText(qt_("&Default..."));
+       colorModule->mainTextCF->setStyleSheet(QLatin1String(""));
+       colorModule->mainTextCF->setVisible(false);
        // save default color (black)
        set_fontcolor = rgbFromHexName("#000000");
        is_fontcolor = false;
@@ -2188,50 +2395,52 @@ void GuiDocument::deleteFontColor()
 
 void GuiDocument::changeNoteFontColor()
 {
-       QColor const & newColor = QColorDialog::getColor(
-               rgb2qcolor(set_notefontcolor), asQWidget());
+       QColor const & newColor = getColor(rgb2qcolor(set_notefontcolor));
        if (!newColor.isValid())
                return;
-       // set the button color
-       colorModule->noteFontColorPB->setStyleSheet(
-               colorButtonStyleSheet(newColor));
+       // set the color
+       colorModule->noteFontCF->setStyleSheet(
+               colorFrameStyleSheet(newColor));
        // save color
        set_notefontcolor = rgbFromHexName(fromqstr(newColor.name()));
+       is_notefontcolor = true;
        change_adaptor();
 }
 
 
 void GuiDocument::deleteNoteFontColor()
 {
-       // set the button color back to pref
+       // set the color back to pref
        theApp()->getRgbColor(Color_greyedouttext, set_notefontcolor);
-       colorModule->noteFontColorPB->setStyleSheet(
-               colorButtonStyleSheet(rgb2qcolor(set_notefontcolor)));
+       colorModule->noteFontCF->setStyleSheet(
+               colorFrameStyleSheet(rgb2qcolor(set_notefontcolor)));
+       is_notefontcolor = false;
        change_adaptor();
 }
 
 
 void GuiDocument::changeBoxBackgroundColor()
 {
-       QColor const & newColor = QColorDialog::getColor(
-               rgb2qcolor(set_boxbgcolor), asQWidget());
+       QColor const & newColor = getColor(rgb2qcolor(set_boxbgcolor));
        if (!newColor.isValid())
                return;
-       // set the button color
-       colorModule->boxBackgroundPB->setStyleSheet(
-               colorButtonStyleSheet(newColor));
+       // set the color
+       colorModule->boxBackgroundCF->setStyleSheet(
+               colorFrameStyleSheet(newColor));
        // save color
        set_boxbgcolor = rgbFromHexName(fromqstr(newColor.name()));
+       is_boxbgcolor = true;
        change_adaptor();
 }
 
 
 void GuiDocument::deleteBoxBackgroundColor()
 {
-       // set the button color back to pref
+       // set the color back to pref
        theApp()->getRgbColor(Color_shadedbg, set_boxbgcolor);
-       colorModule->boxBackgroundPB->setStyleSheet(
-               colorButtonStyleSheet(rgb2qcolor(set_boxbgcolor)));
+       colorModule->boxBackgroundCF->setStyleSheet(
+               colorFrameStyleSheet(rgb2qcolor(set_boxbgcolor)));
+       is_boxbgcolor = false;
        change_adaptor();
 }
 
@@ -2242,26 +2451,45 @@ void GuiDocument::updateQuoteStyles(bool const set)
                fromqstr(langModule->languageCO->itemData(
                        langModule->languageCO->currentIndex()).toString()));
 
-       InsetQuotesParams::QuoteStyle def = bp_.getQuoteStyle(lang->quoteStyle());
+       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)
+               QuoteStyle qs = QuoteStyle(i);
+               if (qs == QuoteStyle::Dynamic)
                        continue;
                bool const langdef = (qs == def);
                if (langdef) {
                        // add the default style on top
                        langModule->quoteStyleCO->insertItem(0,
-                               toqstr(quoteparams.getGuiLabel(qs, langdef)), qs);
+                               toqstr(quoteparams.getGuiLabel(qs, langdef)), static_cast<int>(qs));
                        has_default = true;
                }
                else
                        langModule->quoteStyleCO->addItem(
-                               toqstr(quoteparams.getGuiLabel(qs, langdef)), qs);
+                               toqstr(quoteparams.getGuiLabel(qs, langdef)), static_cast<int>(qs));
        }
+       // Use document serif font to assure quotation marks are distinguishable
+       QFont comboFont(toqstr(lyxrc.roman_font_name),
+                       langModule->quoteStyleCO->fontInfo().pointSize() * 1.4, -1, false);
+       QFontMetrics fm(comboFont);
+       // calculate width of the widest item in the set font
+       int qswidth = 0;
+       for (int i = 0; i < langModule->quoteStyleCO->count(); ++i) {
+               langModule->quoteStyleCO->setItemData(i, QVariant(comboFont), Qt::FontRole);
+               QString str = langModule->quoteStyleCO->itemText(i);
+#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
+               qswidth = max(qswidth, fm.horizontalAdvance(str));
+#else
+               qswidth = max(qswidth, fm.width(str));
+#endif
+       }
+       // add scrollbar width and margin to width
+       qswidth += langModule->quoteStyleCO->style()->pixelMetric(QStyle::PM_ScrollBarExtent);
+       qswidth += langModule->quoteStyleCO->view()->autoScrollMargin();
+       langModule->quoteStyleCO->view()->setMinimumWidth(qswidth);
        if (set && has_default)
                // (re)set to the default style
                langModule->quoteStyleCO->setCurrentIndex(0);
@@ -2274,7 +2502,7 @@ void GuiDocument::languageChanged(int i)
        Language const * lang = lyx::languages.getLanguage(
                fromqstr(langModule->languageCO->itemData(i).toString()));
        if (lang->babel().empty() && !lang->polyglossia().empty()
-               && lang->requires() != "CJK" && lang->requires() != "japanese") {
+               && lang->required() != "CJK" && lang->required() != "japanese") {
                        // If we force to switch fontspec on, store
                        // current state (#8717)
                        if (fontModule->osFontsCB->isEnabled())
@@ -2301,12 +2529,12 @@ 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_roman = fontModule->fontsRomanCO->getData(
+                       fontModule->fontsRomanCO->currentIndex());
+       QString const font_sans = fontModule->fontsSansCO->getData(
+                       fontModule->fontsSansCO->currentIndex());
+       QString const font_typewriter = fontModule->fontsTypewriterCO->getData(
+                       fontModule->fontsTypewriterCO->currentIndex());
        QString const font_math = fontModule->fontsMathCO->itemData(
                        fontModule->fontsMathCO->currentIndex()).toString();
        int const font_sf_scale = fontModule->scaleSansSB->value();
@@ -2325,15 +2553,12 @@ void GuiDocument::osFontsChanged(bool nontexfonts)
        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);
+       if (!fontModule->font_roman.isEmpty())
+               fontModule->fontsRomanCO->set(fontModule->font_roman);
+       if (!fontModule->font_sans.isEmpty())
+               fontModule->fontsSansCO->set(fontModule->font_sans);
+       if (!fontModule->font_typewriter.isEmpty())
+               fontModule->fontsTypewriterCO->set(fontModule->font_typewriter);
        index = fontModule->fontsMathCO->findData(fontModule->font_math);
        if (index != -1)
                fontModule->fontsMathCO->setCurrentIndex(index);
@@ -2349,8 +2574,6 @@ void GuiDocument::osFontsChanged(bool nontexfonts)
        langModule->encodingCO->setEnabled(tex_fonts);
        inputencodingToDialog();
 
-       fontModule->fontsDefaultCO->setEnabled(tex_fonts);
-       fontModule->fontsDefaultLA->setEnabled(tex_fonts);
        fontModule->cjkFontLE->setEnabled(tex_fonts);
        fontModule->cjkFontLA->setEnabled(tex_fonts);
 
@@ -2374,6 +2597,18 @@ void GuiDocument::encodingSwitched(int i)
        langModule->unicodeEncodingCO->setVisible(i == EncodingSets::unicode);
        langModule->autoEncodingCO->setVisible(i == EncodingSets::legacy);
        langModule->customEncodingCO->setVisible(i == EncodingSets::custom);
+       switch (i) {
+       case EncodingSets::unicode:
+               langModule->encodingVariantLA->setBuddy(langModule->unicodeEncodingCO);
+               break;
+       case EncodingSets::legacy:
+               langModule->encodingVariantLA->setBuddy(langModule->autoEncodingCO);
+               break;
+       case EncodingSets::custom:
+               langModule->encodingVariantLA->setBuddy(langModule->customEncodingCO);
+               break;
+       }
        if (tex_fonts)
                langModule->unicodeEncodingCO->setItemText(1, qt_("Direct (No inputenc)"));
        else
@@ -2428,8 +2663,8 @@ void GuiDocument::fontOsfToggled(bool state)
 {
        if (fontModule->osFontsCB->isChecked())
                return;
-       QString font = fontModule->fontsRomanCO->itemData(
-                       fontModule->fontsRomanCO->currentIndex()).toString();
+       QString font = fontModule->fontsRomanCO->getData(
+                       fontModule->fontsRomanCO->currentIndex());
        if (hasMonolithicExpertSet(font))
                fontModule->fontScCB->setChecked(state);
 }
@@ -2439,8 +2674,8 @@ void GuiDocument::fontScToggled(bool state)
 {
        if (fontModule->osFontsCB->isChecked())
                return;
-       QString font = fontModule->fontsRomanCO->itemData(
-                       fontModule->fontsRomanCO->currentIndex()).toString();
+       QString font = fontModule->fontsRomanCO->getData(
+                       fontModule->fontsRomanCO->currentIndex());
        if (hasMonolithicExpertSet(font))
                fontModule->fontOsfCB->setChecked(state);
 }
@@ -2448,50 +2683,40 @@ void GuiDocument::fontScToggled(bool state)
 
 void GuiDocument::updateExtraOpts()
 {
-       bool const tex_fonts = !fontModule->osFontsCB->isChecked();
-       QString font;
-       if (tex_fonts)
-               font = fontModule->fontsRomanCO->itemData(
-                               fontModule->fontsRomanCO->currentIndex()).toString();
+       QString font = fontModule->fontsRomanCO->getData(
+                       fontModule->fontsRomanCO->currentIndex());
        bool const rm_opts = providesExtraOpts(font);
-       if (tex_fonts)
-               font = fontModule->fontsSansCO->itemData(
-                               fontModule->fontsSansCO->currentIndex()).toString();
+       font = fontModule->fontsSansCO->getData(
+                       fontModule->fontsSansCO->currentIndex());
        bool const sf_opts = providesExtraOpts(font);
-       if (tex_fonts)
-               font = fontModule->fontsTypewriterCO->itemData(
-                               fontModule->fontsTypewriterCO->currentIndex()).toString();
+       font = fontModule->fontsTypewriterCO->getData(
+                       fontModule->fontsTypewriterCO->currentIndex());
        bool const tt_opts = providesExtraOpts(font);
-       fontModule->fontspecRomanLA->setEnabled(!tex_fonts || rm_opts);
-       fontModule->fontspecRomanLE->setEnabled(!tex_fonts || rm_opts);
-       fontModule->fontspecSansLA->setEnabled(!tex_fonts || sf_opts);
-       fontModule->fontspecSansLE->setEnabled(!tex_fonts || sf_opts);
-       fontModule->fontspecTypewriterLA->setEnabled(!tex_fonts || tt_opts);
-       fontModule->fontspecTypewriterLE->setEnabled(!tex_fonts || tt_opts);
+       fontModule->fontspecRomanLA->setEnabled(rm_opts);
+       fontModule->fontspecRomanLE->setEnabled(rm_opts);
+       fontModule->fontspecSansLA->setEnabled(sf_opts);
+       fontModule->fontspecSansLE->setEnabled(sf_opts);
+       fontModule->fontspecTypewriterLA->setEnabled(tt_opts);
+       fontModule->fontspecTypewriterLE->setEnabled(tt_opts);
 }
 
 
 void GuiDocument::updateFontOptions()
 {
-       bool const tex_fonts = !fontModule->osFontsCB->isChecked();
-       QString font;
-       if (tex_fonts)
-               font = fontModule->fontsSansCO->itemData(
-                               fontModule->fontsSansCO->currentIndex()).toString();
-       bool scaleable = providesScale(font);
-       fontModule->scaleSansSB->setEnabled(scaleable);
-       fontModule->scaleSansLA->setEnabled(scaleable);
+       QString font = fontModule->fontsSansCO->getData(
+                       fontModule->fontsSansCO->currentIndex());
+       bool scalable = providesScale(font);
+       fontModule->scaleSansSB->setEnabled(scalable);
+       fontModule->scaleSansLA->setEnabled(scalable);
        fontModule->fontSansOsfCB->setEnabled(providesOSF(font));
-       if (tex_fonts)
-               font = fontModule->fontsTypewriterCO->itemData(
-                               fontModule->fontsTypewriterCO->currentIndex()).toString();
-       scaleable = providesScale(font);
-       fontModule->scaleTypewriterSB->setEnabled(scaleable);
-       fontModule->scaleTypewriterLA->setEnabled(scaleable);
+       font = fontModule->fontsTypewriterCO->getData(
+                       fontModule->fontsTypewriterCO->currentIndex());
+       scalable = providesScale(font);
+       fontModule->scaleTypewriterSB->setEnabled(scalable);
+       fontModule->scaleTypewriterLA->setEnabled(scalable);
        fontModule->fontTypewriterOsfCB->setEnabled(providesOSF(font));
-       if (tex_fonts)
-               font = fontModule->fontsRomanCO->itemData(
-                               fontModule->fontsRomanCO->currentIndex()).toString();
+       font = fontModule->fontsRomanCO->getData(
+                       fontModule->fontsRomanCO->currentIndex());
        fontModule->fontScCB->setEnabled(providesSC(font));
        fontModule->fontOsfCB->setEnabled(providesOSF(font));
        updateExtraOpts();
@@ -2534,10 +2759,10 @@ bool GuiDocument::ot1() const
 
 bool GuiDocument::completeFontset() const
 {
-       return (fontModule->fontsSansCO->itemData(
-                       fontModule->fontsSansCO->currentIndex()).toString() == "default"
-               && fontModule->fontsSansCO->itemData(
-                       fontModule->fontsTypewriterCO->currentIndex()).toString() == "default");
+       return (fontModule->fontsSansCO->getData(
+                       fontModule->fontsSansCO->currentIndex()) == "default"
+               && fontModule->fontsSansCO->getData(
+                       fontModule->fontsTypewriterCO->currentIndex()) == "default");
 }
 
 
@@ -2578,6 +2803,10 @@ void GuiDocument::updateTexFonts()
 
 void GuiDocument::updateFontlist()
 {
+       // reset the filters of the CategorizedCombos
+       fontModule->fontsRomanCO->resetFilter();
+       fontModule->fontsSansCO->resetFilter();
+       fontModule->fontsTypewriterCO->resetFilter();
        fontModule->fontsRomanCO->clear();
        fontModule->fontsSansCO->clear();
        fontModule->fontsTypewriterCO->clear();
@@ -2585,21 +2814,37 @@ void GuiDocument::updateFontlist()
 
        // 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"));
-               fontModule->fontsTypewriterCO->addItem(qt_("Default"), QString("default"));
+               fontModule->fontsRomanCO->addItemSort(QString("default"), qt_("Default"),
+                                                     QString(), qt_("Default font (as set by class)"),
+                                                     false, false, false, true, true);
+               fontModule->fontsSansCO->addItemSort(QString("default"), qt_("Default"),
+                                                    QString(), qt_("Default font (as set by class)"),
+                                                    false, false, false, true, true);
+               fontModule->fontsTypewriterCO->addItemSort(QString("default"), qt_("Default"),
+                                                          QString(), qt_("Default font (as set by class)"),
+                                                          false, false, false, true, true);
                QString unimath = qt_("Non-TeX Fonts Default");
                if (!LaTeXFeatures::isAvailable("unicode-math"))
                        unimath += qt_(" (not available)");
                fontModule->fontsMathCO->addItem(qt_("Class Default (TeX Fonts)"), QString("auto"));
                fontModule->fontsMathCO->addItem(unimath, QString("default"));
 
+#if QT_VERSION >= 0x060000
+               const QStringList families(QFontDatabase::families());
+#else
                QFontDatabase fontdb;
-               QStringList families(fontdb.families());
-               for (QStringList::Iterator it = families.begin(); it != families.end(); ++it) {
-                       fontModule->fontsRomanCO->addItem(*it, *it);
-                       fontModule->fontsSansCO->addItem(*it, *it);
-                       fontModule->fontsTypewriterCO->addItem(*it, *it);
+               const QStringList families(fontdb.families());
+#endif
+               for (auto const & family : families) {
+                       fontModule->fontsRomanCO->addItemSort(family, family,
+                                                             QString(), QString(),
+                                                             false, false, false, true, true);
+                       fontModule->fontsSansCO->addItemSort(family, family,
+                                                            QString(), QString(),
+                                                            false, false, false, true, true);
+                       fontModule->fontsTypewriterCO->addItemSort(family, family,
+                                                                  QString(), QString(),
+                                                                  false, false, false, true, true);
                }
                return;
        }
@@ -2607,24 +2852,36 @@ void GuiDocument::updateFontlist()
        if (rmfonts_.empty())
                updateTexFonts();
 
-       fontModule->fontsRomanCO->addItem(qt_("Default"), QString("default"));
+       fontModule->fontsRomanCO->addItemSort(QString("default"), qt_("Default"),
+                                             QString(), qt_("Default font (as set by class)"),
+                                             false, false, false, true, true);
        QMap<QString, QString>::const_iterator rmi = rmfonts_.constBegin();
        while (rmi != rmfonts_.constEnd()) {
-               fontModule->fontsRomanCO->addItem(rmi.key(), rmi.value());
+               fontModule->fontsRomanCO->addItemSort(rmi.value(), rmi.key(),
+                                                     QString(), QString(),
+                                                     false, false, false, true, true);
                ++rmi;
        }
 
-       fontModule->fontsSansCO->addItem(qt_("Default"), QString("default"));
+       fontModule->fontsSansCO->addItemSort(QString("default"), qt_("Default"),
+                                            QString(), qt_("Default font (as set by class)"),
+                                            false, false, false, true, true);
        QMap<QString, QString>::const_iterator sfi = sffonts_.constBegin();
        while (sfi != sffonts_.constEnd()) {
-               fontModule->fontsSansCO->addItem(sfi.key(), sfi.value());
+               fontModule->fontsSansCO->addItemSort(sfi.value(), sfi.key(),
+                                                    QString(), QString(),
+                                                    false, false, false, true, true);
                ++sfi;
        }
 
-       fontModule->fontsTypewriterCO->addItem(qt_("Default"), QString("default"));
+       fontModule->fontsTypewriterCO->addItemSort(QString("default"), qt_("Default"),
+                                                  QString(), qt_("Default font (as set by class)"),
+                                                  false, false, false, true, true);
        QMap<QString, QString>::const_iterator tti = ttfonts_.constBegin();
        while (tti != ttfonts_.constEnd()) {
-               fontModule->fontsTypewriterCO->addItem(tti.key(), tti.value());
+               fontModule->fontsTypewriterCO->addItemSort(tti.value(), tti.key(),
+                                                          QString(), QString(),
+                                                          false, false, false, true, true);
                ++tti;
        }
 
@@ -2668,26 +2925,22 @@ void GuiDocument::updateMathFonts(QString const & rm)
 
 void GuiDocument::romanChanged(int item)
 {
+       QString const font = fontModule->fontsRomanCO->getData(item);
+       fontModule->fontOsfCB->setEnabled(providesOSF(font));
+       updateExtraOpts();
        if (fontModule->osFontsCB->isChecked())
                return;
-       QString const font =
-               fontModule->fontsRomanCO->itemData(item).toString();
        fontModule->fontScCB->setEnabled(providesSC(font));
-       fontModule->fontOsfCB->setEnabled(providesOSF(font));
-       updateExtraOpts();
        updateMathFonts(font);
 }
 
 
 void GuiDocument::sansChanged(int item)
 {
-       if (fontModule->osFontsCB->isChecked())
-               return;
-       QString const font =
-               fontModule->fontsSansCO->itemData(item).toString();
-       bool const scaleable = providesScale(font);
-       fontModule->scaleSansSB->setEnabled(scaleable);
-       fontModule->scaleSansLA->setEnabled(scaleable);
+       QString const font = fontModule->fontsSansCO->getData(item);
+       bool const scalable = providesScale(font);
+       fontModule->scaleSansSB->setEnabled(scalable);
+       fontModule->scaleSansLA->setEnabled(scalable);
        fontModule->fontSansOsfCB->setEnabled(providesOSF(font));
        updateExtraOpts();
 }
@@ -2695,13 +2948,10 @@ void GuiDocument::sansChanged(int item)
 
 void GuiDocument::ttChanged(int item)
 {
-       if (fontModule->osFontsCB->isChecked())
-               return;
-       QString const font =
-               fontModule->fontsTypewriterCO->itemData(item).toString();
-       bool scaleable = providesScale(font);
-       fontModule->scaleTypewriterSB->setEnabled(scaleable);
-       fontModule->scaleTypewriterLA->setEnabled(scaleable);
+       QString const font = fontModule->fontsTypewriterCO->getData(item);
+       bool scalable = providesScale(font);
+       fontModule->scaleTypewriterSB->setEnabled(scalable);
+       fontModule->scaleTypewriterLA->setEnabled(scalable);
        fontModule->fontTypewriterOsfCB->setEnabled(providesOSF(font));
        updateExtraOpts();
 }
@@ -2727,9 +2977,9 @@ void GuiDocument::updatePagestyle(string const & items, string const & sel)
 
        int nn = 0;
 
-       for (size_t i = 0; i < pagestyles.size(); ++i)
-               if (pagestyles[i].first == sel)
-                       nn = pageLayoutModule->pagestyleCO->findText(pagestyles[i].second);
+       for (auto const & pagestyle : pagestyles)
+               if (pagestyle.first == sel)
+                       nn = pageLayoutModule->pagestyleCO->findText(pagestyle.second);
 
        if (nn > 0)
                pageLayoutModule->pagestyleCO->setCurrentIndex(nn);
@@ -2971,8 +3221,8 @@ void GuiDocument::updateEngineDependends()
                                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");
+       bool const citepack = ce->required("biblatex.sty") || ce->required("jurabib.sty")
+                       || ce->required("natbib.sty");
        biblioModule->citePackageOptionsLE->setEnabled(citepack);
        biblioModule->citePackageOptionsL->setEnabled(citepack);
 }
@@ -3032,10 +3282,7 @@ void GuiDocument::updateEngineType(string const & items, CiteEngineType const &
 {
        engine_types_.clear();
 
-       int nn = 0;
-
        for (int n = 0; !token(items, '|', n).empty(); ++n) {
-               nn += 1;
                string style = token(items, '|', n);
                engine_types_.push_back(style);
        }
@@ -3167,6 +3414,9 @@ void GuiDocument::updateModuleInfo()
        }
        QModelIndex const & idx = lv->selectionModel()->currentIndex();
 
+       if (!idx.isValid())
+               return;
+
        if (!focus_on_selected
            && modules_av_model_.itemFromIndex(idx)->hasChildren()) {
                // This is a category header
@@ -3287,7 +3537,7 @@ void GuiDocument::getTableStyles()
             << toqstr(system);
 
        for (int i = 0; i < dirs.size(); ++i) {
-               QString const dir = dirs.at(i);
+               QString const dir = dirs.at(i);
                QDirIterator it(dir, QDir::Files, QDirIterator::Subdirectories);
                while (it.hasNext()) {
                        QString fn = QFileInfo(it.next()).fileName();
@@ -3343,6 +3593,16 @@ bool GuiDocument::isChildIncluded(string const & child)
 
 void GuiDocument::applyView()
 {
+       // auto-validate local layout
+       if (!localLayout->isValid()) {
+               localLayout->validate();
+               if (!localLayout->isValid()) {
+                       setApplyStopped(true);
+                       docPS->setCurrentPanel(N_("Local Layout"));
+                       return;
+               }
+       }
+
        // preamble
        preambleModule->apply(bp_);
        localLayout->apply(bp_);
@@ -3350,6 +3610,7 @@ void GuiDocument::applyView()
        // date
        bp_.suppress_date = latexModule->suppressDateCB->isChecked();
        bp_.use_refstyle  = latexModule->refstyleCB->isChecked();
+       bp_.use_formatted_ref  = latexModule->refFormattedCB->isChecked();
 
        // biblio
        string const engine =
@@ -3416,8 +3677,8 @@ void GuiDocument::applyView()
                        // this should never happen
                        bp_.inputenc = "utf8";
        }
-       bp_.quotes_style = (InsetQuotesParams::QuoteStyle) langModule->quoteStyleCO->itemData(
-               langModule->quoteStyleCO->currentIndex()).toInt();
+       bp_.quotes_style = QuoteStyle(langModule->quoteStyleCO->itemData(
+               langModule->quoteStyleCO->currentIndex()).toInt());
        bp_.dynamic_quotes = langModule->dynamicQuotesCB->isChecked();
 
        QString const langname = langModule->languageCO->itemData(
@@ -3445,7 +3706,14 @@ void GuiDocument::applyView()
        bp_.fontcolor = set_fontcolor;
        bp_.isfontcolor = is_fontcolor;
        bp_.notefontcolor = set_notefontcolor;
+       bp_.isnotefontcolor = is_notefontcolor;
+       if (is_notefontcolor) {
+               // Set information used in statusbar (#12130)
+               lcolor.setColor("notefontcolor", lyx::X11hexname(set_notefontcolor));
+               lcolor.setGUIName("notefontcolor", N_("greyedout inset text"));
+       }
        bp_.boxbgcolor = set_boxbgcolor;
+       bp_.isboxbgcolor = is_boxbgcolor;
 
        // numbering
        if (bp_.documentClass().hasTocLevels()) {
@@ -3503,21 +3771,13 @@ void GuiDocument::applyView()
        bp_.is_math_indent = mathsModule->MathIndentCB->isChecked();
        if (bp_.is_math_indent) {
                // if formulas are indented
-               switch (mathsModule->MathIndentCO->currentIndex()) {
-               case 0:
-                       bp_.setMathIndent(Length());
-                       break;
-               case 1: {
+               if (mathsModule->MathIndentCO->itemData(mathsModule->MathIndentCO->currentIndex()) == "custom") {
                        Length mathindent(widgetsToLength(mathsModule->MathIndentLE,
                                                          mathsModule->MathIndentLengthCO));
                        bp_.setMathIndent(mathindent);
-                       break;
-               }
-               default:
-                       // this should never happen
+               } else
+                       // default
                        bp_.setMathIndent(Length());
-                       break;
-               }
        }
        switch (mathsModule->MathNumberingPosCO->currentIndex()) {
                case 0:
@@ -3576,43 +3836,34 @@ void GuiDocument::applyView()
        if (textLayoutModule->indentRB->isChecked()) {
                // if paragraphs are separated by an indentation
                bp_.paragraph_separation = BufferParams::ParagraphIndentSeparation;
-               switch (textLayoutModule->indentCO->currentIndex()) {
-               case 0:
-                       bp_.setParIndent(Length());
-                       break;
-               case 1: {
+               if (textLayoutModule->indentCO->itemData(textLayoutModule->indentCO->currentIndex()) == "custom") {
                        Length parindent(widgetsToLength(textLayoutModule->indentLE,
                                                         textLayoutModule->indentLengthCO));
                        bp_.setParIndent(parindent);
-                       break;
-               }
-               default:
-                       // this should never happen
+               } else
+                       // default
                        bp_.setParIndent(Length());
-                       break;
-               }
        } else {
                // if paragraphs are separated by a skip
                bp_.paragraph_separation = BufferParams::ParagraphSkipSeparation;
-               switch (textLayoutModule->skipCO->currentIndex()) {
-               case 0:
-                       bp_.setDefSkip(VSpace(VSpace::SMALLSKIP));
-                       break;
-               case 1:
-                       bp_.setDefSkip(VSpace(VSpace::MEDSKIP));
-                       break;
-               case 2:
-                       bp_.setDefSkip(VSpace(VSpace::BIGSKIP));
+               VSpace::VSpaceKind spacekind =
+                       VSpace::VSpaceKind(textLayoutModule->skipCO->itemData(textLayoutModule->skipCO->currentIndex()).toInt());
+               switch (spacekind) {
+               case VSpace::SMALLSKIP:
+               case VSpace::MEDSKIP:
+               case VSpace::BIGSKIP:
+               case VSpace::HALFLINE:
+               case VSpace::FULLLINE:
+                       bp_.setDefSkip(VSpace(spacekind));
                        break;
-               case 3:
-                       {
+               case VSpace::LENGTH: {
                        VSpace vs = VSpace(
                                widgetsToLength(textLayoutModule->skipLE,
                                textLayoutModule->skipLengthCO)
                                );
                        bp_.setDefSkip(vs);
                        break;
-                       }
+               }
                default:
                        // this should never happen
                        bp_.setDefSkip(VSpace(VSpace::MEDSKIP));
@@ -3636,14 +3887,23 @@ void GuiDocument::applyView()
 
        // Master/Child
        bp_.clearIncludedChildren();
+       updateIncludeonlys();
        if (masterChildModule->includeonlyRB->isChecked()) {
                list<string>::const_iterator it = includeonlys_.begin();
                for (; it != includeonlys_.end() ; ++it) {
                        bp_.addIncludedChildren(*it);
                }
        }
-       bp_.maintain_unincluded_children =
-               masterChildModule->maintainAuxCB->isChecked();
+       if (masterChildModule->maintainCRNoneRB->isChecked())
+               bp_.maintain_unincluded_children =
+                       BufferParams::CM_None;
+       else if (masterChildModule->maintainCRMostlyRB->isChecked())
+               bp_.maintain_unincluded_children =
+                       BufferParams::CM_Mostly;
+       else
+               bp_.maintain_unincluded_children =
+                       BufferParams::CM_Strict;
+       updateIncludeonlyDisplay();
 
        // Float Settings
        bp_.float_placement = floatModule->getPlacement();
@@ -3686,6 +3946,18 @@ void GuiDocument::applyView()
        bp_.html_math_img_scale = outputModule->mathimgSB->value();
        bp_.display_pixel_ratio = theGuiApp()->pixelRatio();
 
+       int tablefmt = outputModule->tableoutCB->currentIndex();
+       if (tablefmt == -1)
+               tablefmt = 0;
+       auto const to = static_cast<BufferParams::TableOutput>(tablefmt);
+       bp_.docbook_table_output = to;
+
+       int mathmlprefix = outputModule->mathmlprefixCB->currentIndex();
+       if (mathmlprefix == -1)
+               mathmlprefix = 0;
+       auto const mp = static_cast<BufferParams::MathMLNameSpacePrefix>(mathmlprefix);
+       bp_.docbook_mathml_prefix = mp;
+
        bp_.save_transient_properties =
                outputModule->saveTransientPropertiesCB->isChecked();
        bp_.postpone_fragile_content =
@@ -3694,19 +3966,19 @@ void GuiDocument::applyView()
        // fonts
        bp_.fonts_roman[nontexfonts] =
                fromqstr(fontModule->fontsRomanCO->
-                       itemData(fontModule->fontsRomanCO->currentIndex()).toString());
+                       getData(fontModule->fontsRomanCO->currentIndex()));
        bp_.fonts_roman[!nontexfonts] = fromqstr(fontModule->font_roman);
        bp_.font_roman_opts = fromqstr(fontModule->fontspecRomanLE->text());
 
        bp_.fonts_sans[nontexfonts] =
                fromqstr(fontModule->fontsSansCO->
-                       itemData(fontModule->fontsSansCO->currentIndex()).toString());
+                       getData(fontModule->fontsSansCO->currentIndex()));
        bp_.fonts_sans[!nontexfonts] = fromqstr(fontModule->font_sans);
        bp_.font_sans_opts = fromqstr(fontModule->fontspecSansLE->text());
 
        bp_.fonts_typewriter[nontexfonts] =
                fromqstr(fontModule->fontsTypewriterCO->
-                       itemData(fontModule->fontsTypewriterCO->currentIndex()).toString());
+                       getData(fontModule->fontsTypewriterCO->currentIndex()));
        bp_.fonts_typewriter[!nontexfonts] = fromqstr(fontModule->font_typewriter);
        bp_.font_typewriter_opts = fromqstr(fontModule->fontspecTypewriterLE->text());
 
@@ -3740,11 +4012,8 @@ void GuiDocument::applyView()
        bp_.fonts_sans_osf = fontModule->fontSansOsfCB->isChecked();
        bp_.fonts_typewriter_osf = fontModule->fontTypewriterOsfCB->isChecked();
 
-       if (nontexfonts)
-               bp_.fonts_default_family = "default";
-       else
-               bp_.fonts_default_family = GuiDocument::fontfamilies[
-                       fontModule->fontsDefaultCO->currentIndex()];
+       bp_.fonts_default_family = GuiDocument::fontfamilies[
+               fontModule->fontsDefaultCO->currentIndex()];
 
        if (fontModule->fontsizeCO->currentIndex() == 0)
                bp_.fontsize = "default";
@@ -3777,14 +4046,16 @@ void GuiDocument::applyView()
 
        Ui::MarginsUi const * m = marginsModule;
 
-       bp_.leftmargin = widgetsToLength(m->innerLE, m->innerUnit);
-       bp_.topmargin = widgetsToLength(m->topLE, m->topUnit);
-       bp_.rightmargin = widgetsToLength(m->outerLE, m->outerUnit);
-       bp_.bottommargin = widgetsToLength(m->bottomLE, m->bottomUnit);
-       bp_.headheight = widgetsToLength(m->headheightLE, m->headheightUnit);
-       bp_.headsep = widgetsToLength(m->headsepLE, m->headsepUnit);
-       bp_.footskip = widgetsToLength(m->footskipLE, m->footskipUnit);
-       bp_.columnsep = widgetsToLength(m->columnsepLE, m->columnsepUnit);
+       if (bp_.use_geometry) {
+               bp_.leftmargin = widgetsToLength(m->innerLE, m->innerUnit);
+               bp_.topmargin = widgetsToLength(m->topLE, m->topUnit);
+               bp_.rightmargin = widgetsToLength(m->outerLE, m->outerUnit);
+               bp_.bottommargin = widgetsToLength(m->bottomLE, m->bottomUnit);
+               bp_.headheight = widgetsToLength(m->headheightLE, m->headheightUnit);
+               bp_.headsep = widgetsToLength(m->headsepLE, m->headsepUnit);
+               bp_.footskip = widgetsToLength(m->footskipLE, m->footskipUnit);
+               bp_.columnsep = widgetsToLength(m->columnsepLE, m->columnsepUnit);
+       }
 
        // branches
        branchesModule->apply(bp_);
@@ -3813,7 +4084,9 @@ void GuiDocument::applyView()
        else
                pdf.pagemode.clear();
        pdf.quoted_options = pdf.quoted_options_check(
-                               fromqstr(pdfSupportModule->optionsLE->text()));
+                               fromqstr(pdfSupportModule->optionsTE->toPlainText()));
+       bp_.document_metadata = qstring_to_ucs4(pdfSupportModule->metadataTE->toPlainText()
+                                               .trimmed().replace(QRegularExpression("\n+"), "\n"));
 
        // change tracking
        bp_.track_changes = changesModule->trackChangesCB->isChecked();
@@ -3844,6 +4117,7 @@ void GuiDocument::paramsToDialog()
        // date
        latexModule->suppressDateCB->setChecked(bp_.suppress_date);
        latexModule->refstyleCB->setChecked(bp_.use_refstyle);
+       latexModule->refFormattedCB->setChecked(bp_.use_formatted_ref);
 
        // biblio
        string const cite_engine = bp_.citeEngine();
@@ -3893,17 +4167,17 @@ void GuiDocument::paramsToDialog()
        string options =
                split(bp_.bibtex_command, command, ' ');
 
-       int const bpos = biblioModule->bibtexCO->findData(toqstr(command));
-       if (bpos != -1) {
-               biblioModule->bibtexCO->setCurrentIndex(bpos);
-               biblioModule->bibtexOptionsLE->setText(toqstr(options).trimmed());
-       } else {
-               // We reset to default if we do not know the specified compiler
-               // This is for security reasons
-               biblioModule->bibtexCO->setCurrentIndex(
-                       biblioModule->bibtexCO->findData(toqstr("default")));
-               biblioModule->bibtexOptionsLE->clear();
+       int bpos = biblioModule->bibtexCO->findData(toqstr(command));
+       if (bpos == -1) {
+               // We add and set the unknown compiler, indicating that it is unavailable
+               // to assure document compilation and for security reasons, a fallback
+               // will be used on document processing stage
+               biblioModule->bibtexCO->addItem(toqstr(bformat(_("%1$s (not available)"),
+                                                       from_utf8(command))), toqstr(command));
+               bpos = biblioModule->bibtexCO->findData(toqstr(command));
        }
+       biblioModule->bibtexCO->setCurrentIndex(bpos);
+       biblioModule->bibtexOptionsLE->setText(toqstr(options).trimmed());
        biblioModule->bibtexOptionsLE->setEnabled(
                biblioModule->bibtexCO->currentIndex() != 0);
 
@@ -3923,7 +4197,7 @@ void GuiDocument::paramsToDialog()
        updateQuoteStyles();
 
        langModule->quoteStyleCO->setCurrentIndex(
-               langModule->quoteStyleCO->findData(bp_.quotes_style));
+               langModule->quoteStyleCO->findData(static_cast<int>(bp_.quotes_style)));
        langModule->dynamicQuotesCB->setChecked(bp_.dynamic_quotes);
 
        // LaTeX input encoding: set after the fonts (see below)
@@ -3940,26 +4214,32 @@ void GuiDocument::paramsToDialog()
 
        //color
        if (bp_.isfontcolor) {
-               colorModule->fontColorPB->setStyleSheet(
-                       colorButtonStyleSheet(rgb2qcolor(bp_.fontcolor)));
-       }
+               colorModule->mainTextCF->setStyleSheet(
+                       colorFrameStyleSheet(rgb2qcolor(bp_.fontcolor)));
+               colorModule->mainTextCF->setVisible(true);
+       } else
+               colorModule->mainTextCF->setVisible(false);
        set_fontcolor = bp_.fontcolor;
        is_fontcolor = bp_.isfontcolor;
 
-       colorModule->noteFontColorPB->setStyleSheet(
-               colorButtonStyleSheet(rgb2qcolor(bp_.notefontcolor)));
+       colorModule->noteFontCF->setStyleSheet(
+               colorFrameStyleSheet(rgb2qcolor(bp_.notefontcolor)));
        set_notefontcolor = bp_.notefontcolor;
+       is_notefontcolor = bp_.isnotefontcolor;
 
        if (bp_.isbackgroundcolor) {
-               colorModule->backgroundPB->setStyleSheet(
-                       colorButtonStyleSheet(rgb2qcolor(bp_.backgroundcolor)));
-       }
+               colorModule->pageBackgroundCF->setStyleSheet(
+                       colorFrameStyleSheet(rgb2qcolor(bp_.backgroundcolor)));
+               colorModule->pageBackgroundCF->setVisible(true);
+       } else
+               colorModule->pageBackgroundCF->setVisible(false);
        set_backgroundcolor = bp_.backgroundcolor;
        is_backgroundcolor = bp_.isbackgroundcolor;
 
-       colorModule->boxBackgroundPB->setStyleSheet(
-               colorButtonStyleSheet(rgb2qcolor(bp_.boxbgcolor)));
+       colorModule->boxBackgroundCF->setStyleSheet(
+               colorFrameStyleSheet(rgb2qcolor(bp_.boxbgcolor)));
        set_boxbgcolor = bp_.boxbgcolor;
+       is_boxbgcolor = bp_.isboxbgcolor;
 
        // numbering
        int const min_toclevel = documentClass().min_toclevel();
@@ -4077,43 +4357,26 @@ void GuiDocument::paramsToDialog()
        if (bp_.paragraph_separation == BufferParams::ParagraphIndentSeparation) {
                textLayoutModule->indentRB->setChecked(true);
                string parindent = bp_.getParIndent().asString();
-               int indent = 0;
+               QString indent = toqstr("default");
                if (!parindent.empty()) {
                        lengthToWidgets(textLayoutModule->indentLE,
                                        textLayoutModule->indentLengthCO,
                                        parindent, default_unit);
-                       indent = 1;
+                       indent = toqstr("custom");
                }
-               textLayoutModule->indentCO->setCurrentIndex(indent);
-               setIndent(indent);
+               textLayoutModule->indentCO->setCurrentIndex(textLayoutModule->indentCO->findData(indent));
+               setIndent(textLayoutModule->indentCO->currentIndex());
        } else {
                textLayoutModule->skipRB->setChecked(true);
-               int skip = 0;
-               switch (bp_.getDefSkip().kind()) {
-               case VSpace::SMALLSKIP:
-                       skip = 0;
-                       break;
-               case VSpace::MEDSKIP:
-                       skip = 1;
-                       break;
-               case VSpace::BIGSKIP:
-                       skip = 2;
-                       break;
-               case VSpace::LENGTH:
-                       {
-                       skip = 3;
+               VSpace::VSpaceKind skip = bp_.getDefSkip().kind();
+               textLayoutModule->skipCO->setCurrentIndex(textLayoutModule->skipCO->findData(skip));
+               if (skip == VSpace::LENGTH) {
                        string const length = bp_.getDefSkip().asLyXCommand();
                        lengthToWidgets(textLayoutModule->skipLE,
                                textLayoutModule->skipLengthCO,
                                length, default_unit);
-                       break;
-                       }
-               default:
-                       skip = 0;
-                       break;
                }
-               textLayoutModule->skipCO->setCurrentIndex(skip);
-               setSkip(skip);
+               setSkip(textLayoutModule->skipCO->currentIndex());
        }
 
        textLayoutModule->twoColumnCB->setChecked(
@@ -4172,9 +4435,20 @@ void GuiDocument::paramsToDialog()
                masterChildModule->setEnabled(true);
                includeonlys_ = bp_.getIncludedChildren();
                updateIncludeonlys();
+               updateIncludeonlyDisplay();
+       }
+       switch (bp_.maintain_unincluded_children) {
+       case BufferParams::CM_None:
+               masterChildModule->maintainCRNoneRB->setChecked(true);
+               break;
+       case BufferParams::CM_Mostly:
+               masterChildModule->maintainCRMostlyRB->setChecked(true);
+               break;
+       case BufferParams::CM_Strict:
+       default:
+               masterChildModule->maintainCRStrictRB->setChecked(true);
+               break;
        }
-       masterChildModule->maintainAuxCB->setChecked(
-               bp_.maintain_unincluded_children);
 
        // Float Settings
        floatModule->setPlacement(bp_.float_placement);
@@ -4196,7 +4470,7 @@ void GuiDocument::paramsToDialog()
                        langModule->languageCO->currentIndex()).toString()));
        bool const need_fontspec =
                lang->babel().empty() && !lang->polyglossia().empty()
-               && lang->requires() != "CJK" && lang->requires() != "japanese";
+               && lang->required() != "CJK" && lang->required() != "japanese";
        bool const os_fonts_available =
                bp_.baseClass()->outputType() == lyx::LATEX
                && LaTeXFeatures::isAvailable("fontspec");
@@ -4207,30 +4481,36 @@ void GuiDocument::paramsToDialog()
                        bp_.fontsize);
 
        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);
+       bool foundfont = fontModule->fontsRomanCO->set(font, false);
+       if (!foundfont) {
+               fontModule->fontsRomanCO->addItemSort(font, font + qt_(" (not installed)"),
+                                                     qt_("Uninstalled used fonts"),
+                                                     qt_("This font is not installed and won't be used in output"),
+                                                     false, false, false, true);
+               fontModule->fontsRomanCO->set(font);
        }
-       fontModule->fontsRomanCO->setCurrentIndex(rpos);
        fontModule->font_roman = toqstr(bp_.fonts_roman[!bp_.useNonTeXFonts]);
 
        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);
+       foundfont = fontModule->fontsSansCO->set(font, false);
+       if (!foundfont) {
+               fontModule->fontsSansCO->addItemSort(font, font + qt_(" (not installed)"),
+                                                    qt_("Uninstalled used fonts"),
+                                                    qt_("This font is not installed and won't be used in output"),
+                                                    false, false, false, true);
+               fontModule->fontsSansCO->set(font);
        }
-       fontModule->fontsSansCO->setCurrentIndex(spos);
        fontModule->font_sans = toqstr(bp_.fonts_sans[!bp_.useNonTeXFonts]);
 
        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);
+       foundfont = fontModule->fontsTypewriterCO->set(font, false);
+       if (!foundfont) {
+               fontModule->fontsTypewriterCO->addItemSort(font, font + qt_(" (not installed)"),
+                                                          qt_("Uninstalled used fonts"),
+                                                          qt_("This font is not installed and won't be used in output"),
+                                                          false, false, false, true);
+               fontModule->fontsTypewriterCO->set(font);
        }
-       fontModule->fontsTypewriterCO->setCurrentIndex(tpos);
        fontModule->font_typewriter = toqstr(bp_.fonts_typewriter[!bp_.useNonTeXFonts]);
 
        font = toqstr(bp_.fontsMath());
@@ -4250,10 +4530,12 @@ void GuiDocument::paramsToDialog()
                fontModule->fontencLA->setEnabled(true);
                fontModule->fontencCO->setEnabled(true);
                fontModule->fontencLE->setEnabled(true);
-               romanChanged(rpos);
-               sansChanged(spos);
-               ttChanged(tpos);
+               romanChanged(fontModule->fontsRomanCO->currentIndex());
+               sansChanged(fontModule->fontsSansCO->currentIndex());
+               ttChanged(fontModule->fontsTypewriterCO->currentIndex());
        }
+       // Handle options enabling
+       updateFontOptions();
 
        if (!bp_.fonts_cjk.empty())
                fontModule->cjkFontLE->setText(
@@ -4329,6 +4611,9 @@ void GuiDocument::paramsToDialog()
        outputModule->strictCB->setChecked(bp_.html_be_strict);
        outputModule->cssCB->setChecked(bp_.html_css_as_file);
 
+       outputModule->tableoutCB->setCurrentIndex(bp_.docbook_table_output);
+       outputModule->mathmlprefixCB->setCurrentIndex(bp_.docbook_mathml_prefix);
+
        outputModule->saveTransientPropertiesCB
                ->setChecked(bp_.save_transient_properties);
        outputModule->postponeFragileCB
@@ -4360,32 +4645,34 @@ void GuiDocument::paramsToDialog()
        // margins
        Ui::MarginsUi * m = marginsModule;
 
-       setMargins();
+       tmp_leftmargin_ = bp_.leftmargin;
+       tmp_topmargin_ = bp_.topmargin;
+       tmp_rightmargin_ = bp_.rightmargin;
+       tmp_bottommargin_ = bp_.bottommargin;
+       tmp_headheight_ = bp_.headheight;
+       tmp_headsep_ = bp_.headsep;
+       tmp_footskip_ = bp_.footskip;
+       tmp_columnsep_ = bp_.columnsep;
 
        lengthToWidgets(m->topLE, m->topUnit,
                bp_.topmargin, default_unit);
-
        lengthToWidgets(m->bottomLE, m->bottomUnit,
                bp_.bottommargin, default_unit);
-
        lengthToWidgets(m->innerLE, m->innerUnit,
                bp_.leftmargin, default_unit);
-
        lengthToWidgets(m->outerLE, m->outerUnit,
                bp_.rightmargin, default_unit);
-
        lengthToWidgets(m->headheightLE, m->headheightUnit,
                bp_.headheight, default_unit);
-
        lengthToWidgets(m->headsepLE, m->headsepUnit,
                bp_.headsep, default_unit);
-
        lengthToWidgets(m->footskipLE, m->footskipUnit,
                bp_.footskip, default_unit);
-
        lengthToWidgets(m->columnsepLE, m->columnsepUnit,
                bp_.columnsep, default_unit);
 
+       setMargins();
+
        // branches
        updateUnknownBranches();
        branchesModule->update(bp_);
@@ -4407,6 +4694,8 @@ void GuiDocument::paramsToDialog()
        pdfSupportModule->bookmarksopenGB->setChecked(pdf.bookmarksopen);
 
        pdfSupportModule->bookmarksopenlevelSB->setValue(pdf.bookmarksopenlevel);
+       pdfSupportModule->bookmarksopenlevelSB->setEnabled(pdf.bookmarksopen);
+       pdfSupportModule->bookmarksopenlevelLA->setEnabled(pdf.bookmarksopen);
 
        pdfSupportModule->breaklinksCB->setChecked(pdf.breaklinks);
        pdfSupportModule->pdfborderCB->setChecked(pdf.pdfborder);
@@ -4420,9 +4709,12 @@ void GuiDocument::paramsToDialog()
        pdfSupportModule->fullscreenCB->setChecked
                (pdf.pagemode == pdf.pagemode_fullscreen);
 
-       pdfSupportModule->optionsLE->setText(
+       pdfSupportModule->optionsTE->setPlainText(
                toqstr(pdf.quoted_options));
 
+       pdfSupportModule->metadataTE->setPlainText(
+               toqstr(rtrim(bp_.document_metadata, "\n")));
+
        // change tracking
        changesModule->trackChangesCB->setChecked(bp_.track_changes);
        changesModule->outputChangesCB->setChecked(bp_.output_changes);
@@ -4436,6 +4728,10 @@ void GuiDocument::paramsToDialog()
        // clear changed branches cache
        changedBranches_.clear();
 
+       // re-initiate module filter
+       if (!filter_->text().isEmpty())
+               moduleFilterPressed();
+
        // reset trackers
        nonModuleChanged_ = false;
        shellescapeChanged_ = false;
@@ -4458,8 +4754,10 @@ void GuiDocument::updateAvailableModules()
        modInfoList.sort([](modInfoStruct const & a, modInfoStruct const & b) {
                        return 0 < b.name.localeAwareCompare(a.name);
                });
-       QIcon user_icon(getPixmap("images/", "lyxfiles-user", "svgz,png"));
-       QIcon system_icon(getPixmap("images/", "lyxfiles-system", "svgz,png"));
+       QIcon user_icon(guiApp ? guiApp->getScaledPixmap("images/", "lyxfiles-user")
+                              : getPixmap("images/", "lyxfiles-user", "svgz,png"));
+       QIcon system_icon(guiApp ? guiApp->getScaledPixmap("images/", "lyxfiles-system")
+                                : getPixmap("images/", "lyxfiles-system", "svgz,png"));
        int i = 0;
        QFont catfont;
        catfont.setBold(true);
@@ -4508,21 +4806,26 @@ void GuiDocument::updateSelectedModules()
 }
 
 
-void GuiDocument::updateIncludeonlys()
+void GuiDocument::updateIncludeonlyDisplay()
 {
-       masterChildModule->childrenTW->clear();
-       QString const no = qt_("No");
-       QString const yes = qt_("Yes");
-
        if (includeonlys_.empty()) {
                masterChildModule->includeallRB->setChecked(true);
                masterChildModule->childrenTW->setEnabled(false);
-               masterChildModule->maintainAuxCB->setEnabled(false);
+               masterChildModule->maintainGB->setEnabled(false);
        } else {
                masterChildModule->includeonlyRB->setChecked(true);
                masterChildModule->childrenTW->setEnabled(true);
-               masterChildModule->maintainAuxCB->setEnabled(true);
+               masterChildModule->maintainGB->setEnabled(true);
        }
+}
+
+
+void GuiDocument::updateIncludeonlys(bool const cleanup)
+{
+       masterChildModule->childrenTW->clear();
+       QString const no = qt_("No");
+       QString const yes = qt_("Yes");
+
        ListOfBuffers children = buffer().getChildren();
        ListOfBuffers::const_iterator it  = children.begin();
        ListOfBuffers::const_iterator end = children.end();
@@ -4541,17 +4844,10 @@ void GuiDocument::updateIncludeonlys()
                else
                        all_unincluded = false;
        }
-       // Both if all childs are included and if none is included
+       // Both if all children are included and if none is included
        // is equal to "include all" (i.e., omit \includeonly).
-       // Thus, reset the GUI.
-       if (!has_unincluded || all_unincluded) {
-               masterChildModule->includeallRB->setChecked(true);
-               masterChildModule->childrenTW->setEnabled(false);
+       if (cleanup && (!has_unincluded || all_unincluded))
                includeonlys_.clear();
-       }
-       // If all are included, we need to update again.
-       if (!has_unincluded)
-               updateIncludeonlys();
 }
 
 
@@ -4711,7 +5007,7 @@ void GuiDocument::matchBiblatexStyles()
 
 void GuiDocument::updateContents()
 {
-       // Nothing to do here as the document settings is not cursor dependant.
+       // Nothing to do here as the document settings is not cursor dependent.
        return;
 }
 
@@ -4749,35 +5045,15 @@ void GuiDocument::setLayoutComboByIDString(string const & idString)
 
 bool GuiDocument::isValid()
 {
-       return
-               validateListingsParameters().isEmpty() &&
-               localLayout->isValid() &&
-               !localLayout->editing() &&
-               !preambleModule->editing() &&
-               (
-                       // if we're asking for skips between paragraphs
-                       !textLayoutModule->skipRB->isChecked() ||
-                       // then either we haven't chosen custom
-                       textLayoutModule->skipCO->currentIndex() != 3 ||
-                       // or else a length has been given
-                       !textLayoutModule->skipLE->text().isEmpty()
-               ) &&
-               (
-                       // if we're asking for indentation
-                       !textLayoutModule->indentRB->isChecked() ||
-                       // then either we haven't chosen custom
-                       textLayoutModule->indentCO->currentIndex() != 1 ||
-                       // or else a length has been given
-                       !textLayoutModule->indentLE->text().isEmpty()
-               ) &&
-               (
-                       // if we're asking for math indentation
-                       !mathsModule->MathIndentCB->isChecked() ||
-                       // then either we haven't chosen custom
-                       mathsModule->MathIndentCO->currentIndex() != 1 ||
-                       // or else a length has been given
-                       !mathsModule->MathIndentLE->text().isEmpty()
-               );
+       bool const listings_valid = validateListingsParameters().isEmpty();
+       bool const local_layout_valid = !localLayout->editing();
+       bool const preamble_valid = !preambleModule->editing();
+
+       docPS->markPanelValid(N_("Listings[[inset]]"), listings_valid);
+       docPS->markPanelValid(N_("Local Layout"), local_layout_valid && localLayout->isValid());
+       docPS->markPanelValid(N_("LaTeX Preamble"), preamble_valid);
+       
+       return listings_valid && local_layout_valid && preamble_valid;
 }
 
 
@@ -4799,6 +5075,7 @@ bool GuiDocument::initialiseParams(string const &)
                paramsToDialog();
                return true;
        }
+       prev_buffer_filename_ = view->buffer().absFileName();
        bp_ = view->buffer().params();
        loadModuleInfo();
        updateAvailableModules();
@@ -4898,7 +5175,7 @@ void GuiDocument::dispatchParams()
                FileName const master_file = support::makeAbsPath(params().master,
                           support::onlyPath(buffer().absFileName()));
                if (isLyXFileName(master_file.absFileName())) {
-                       Buffer * master = checkAndLoadLyXFile(master_file);
+                       Buffer * master = checkAndLoadLyXFile(master_file, true);
                        if (master) {
                                if (master->isChild(const_cast<Buffer *>(&buffer())))
                                        const_cast<Buffer &>(buffer()).setParent(master);
@@ -4927,7 +5204,13 @@ void GuiDocument::dispatchParams()
                for (; it != end; ++it) {
                        docstring const & current_branch = it->branch();
                        Branch const * branch = branchlist.find(current_branch);
-                       string const x11hexname = X11hexname(branch->color());
+                       string const bcolor = branch->color();
+                       RGBColor rgbcol;
+                       if (bcolor.size() == 7 && bcolor[0] == '#')
+                               rgbcol = lyx::rgbFromHexName(bcolor);
+                       else
+                               guiApp->getRgbColor(lcolor.getFromLyXName(bcolor), rgbcol);
+                       string const x11hexname = X11hexname(rgbcol);
                        // display the new color
                        docstring const str = current_branch + ' ' + from_ascii(x11hexname);
                        dispatch(FuncRequest(LFUN_SET_COLOR, str));
@@ -4981,7 +5264,7 @@ bool GuiDocument::providesOSF(QString const & font) const
        if (fontModule->osFontsCB->isChecked())
                // FIXME: we should check if the fonts really
                // have OSF support. But how?
-               return true;
+               return font != "default";
        return theLaTeXFonts().getLaTeXFont(
                                qstring_to_ucs4(font)).providesOSF(ot1(),
                                                                   completeFontset(),
@@ -5003,7 +5286,7 @@ bool GuiDocument::providesSC(QString const & font) const
 bool GuiDocument::providesScale(QString const & font) const
 {
        if (fontModule->osFontsCB->isChecked())
-               return true;
+               return font != "default";
        return theLaTeXFonts().getLaTeXFont(
                                qstring_to_ucs4(font)).providesScale(ot1(),
                                                                     completeFontset(),
@@ -5014,7 +5297,7 @@ bool GuiDocument::providesScale(QString const & font) const
 bool GuiDocument::providesExtraOpts(QString const & font) const
 {
        if (fontModule->osFontsCB->isChecked())
-               return true;
+               return font != "default";
        return theLaTeXFonts().getLaTeXFont(
                                qstring_to_ucs4(font)).providesMoreOptions(ot1(),
                                                                     completeFontset(),
@@ -5053,7 +5336,7 @@ GuiDocument::modInfoStruct GuiDocument::modInfo(LyXModule const & mod)
        QString const guiname = toqstr(translateIfPossible(from_utf8(mod.getName())));
        m.missingreqs = !isModuleAvailable(mod.getID());
        if (m.missingreqs) {
-               m.name = QString(qt_("%1 (missing req.)")).arg(guiname);
+               m.name = qt_("%1 (missing req.)").arg(guiname);
        } else
                m.name = guiname;
        m.category = mod.category().empty() ? qt_("Miscellaneous")
@@ -5066,7 +5349,7 @@ GuiDocument::modInfoStruct GuiDocument::modInfo(LyXModule const & mod)
                desc.truncate(pos);
        m.local = mod.isLocal();
        QString const mtype = m.local ? qt_("personal module") : qt_("distributed module");
-       QString modulename = QString(qt_("<b>Module name:</b> <i>%1</i> (%2)")).arg(toqstr(m.id)).arg(mtype);
+       QString modulename = qt_("<b>Module name:</b> <i>%1</i> (%2)").arg(toqstr(m.id)).arg(mtype);
        // Tooltip is the desc followed by the module name and the type
        m.description = QString("%1%2")
                .arg(desc.isEmpty() ? QString() : QString("<p>%1</p>").arg(desc),
@@ -5175,8 +5458,22 @@ void GuiDocument::setOutputSync(bool on)
 }
 
 
-
-Dialog * createGuiDocument(GuiView & lv) { return new GuiDocument(lv); }
+bool GuiDocument::eventFilter(QObject * sender, QEvent * event)
+{
+       if (event->type() == QEvent::ApplicationPaletteChange) {
+               // mode switch: colors need to be updated
+               // and the highlighting redone
+               if (pdf_options_highlighter_) {
+                       pdf_options_highlighter_->setupColors();
+                       pdf_options_highlighter_->rehighlight();
+               }
+               if (pdf_metadata_highlighter_) {
+                       pdf_metadata_highlighter_->setupColors();
+                       pdf_metadata_highlighter_->rehighlight();
+               }
+       }
+       return QWidget::eventFilter(sender, event);
+}
 
 
 } // namespace frontend