]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiDocument.cpp
Transfer LyXfunc code to GuiApplication::dispatch() and getStatus(). Now
[lyx.git] / src / frontends / qt4 / GuiDocument.cpp
1 /**
2  * \file GuiDocument.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Edwin Leuven
7  * \author Richard Heck (modules)
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "GuiDocument.h"
15
16 #include "GuiApplication.h"
17 #include "GuiBranches.h"
18 #include "GuiIndices.h"
19 #include "GuiSelectionManager.h"
20 #include "LaTeXHighlighter.h"
21 #include "LengthCombo.h"
22 #include "PanelStack.h"
23 #include "Validator.h"
24
25 #include "LayoutFile.h"
26 #include "BranchList.h"
27 #include "buffer_funcs.h"
28 #include "Buffer.h"
29 #include "BufferParams.h"
30 #include "BufferView.h"
31 #include "Color.h"
32 #include "ColorCache.h"
33 #include "Encoding.h"
34 #include "FloatPlacement.h"
35 #include "Format.h"
36 #include "FuncRequest.h"
37 #include "HSpace.h"
38 #include "IndicesList.h"
39 #include "Language.h"
40 #include "LaTeXFeatures.h"
41 #include "Layout.h"
42 #include "LayoutModuleList.h"
43 #include "LyXRC.h"
44 #include "ModuleList.h"
45 #include "OutputParams.h"
46 #include "PDFOptions.h"
47 #include "qt_helpers.h"
48 #include "Spacing.h"
49
50 #include "insets/InsetListingsParams.h"
51
52 #include "support/debug.h"
53 #include "support/FileName.h"
54 #include "support/filetools.h"
55 #include "support/gettext.h"
56 #include "support/lstrings.h"
57
58 #include "frontends/alert.h"
59
60 #include <QAbstractItemModel>
61 #include <QHeaderView>
62 #include <QColor>
63 #include <QColorDialog>
64 #include <QCloseEvent>
65 #include <QFontDatabase>
66 #include <QScrollBar>
67 #include <QTextCursor>
68
69 #include <sstream>
70 #include <vector>
71
72 #ifdef IN
73 #undef IN
74 #endif
75
76
77 // a style sheet for buttons
78 // this is for example used for the background color setting button
79 static inline QString colorButtonStyleSheet(QColor const & bgColor)
80 {
81         if (bgColor.isValid()) {
82                 QString rc = QLatin1String("background:");
83                 rc += bgColor.name();
84                 return rc;
85         }
86         return QString();
87 }
88
89
90 using namespace std;
91 using namespace lyx::support;
92
93
94 namespace {
95
96 char const * const tex_graphics[] =
97 {
98         "default", "dvialw", "dvilaser", "dvipdf", "dvipdfm", "dvipdfmx",
99         "dvips", "dvipsone", "dvitops", "dviwin", "dviwindo", "dvi2ps", "emtex",
100         "ln", "oztex", "pctexhp", "pctexps", "pctexwin", "pctex32", "pdftex",
101         "psprint", "pubps", "tcidvi", "textures", "truetex", "vtex", "xdvi",
102         "xetex", "none", ""
103 };
104
105
106 char const * const tex_graphics_gui[] =
107 {
108         N_("Default"), "dvialw", "DviLaser", "dvipdf", "DVIPDFM", "DVIPDFMx",
109         "Dvips", "DVIPSONE", "DVItoPS", "DVIWIN", "DVIWindo", "dvi2ps", "EmTeX",
110         "LN", "OzTeX", "pctexhp", "pctexps", "pctexwin", "PCTeX32", "pdfTeX",
111         "psprint", "pubps", "tcidvi", "Textures", "TrueTeX", "VTeX", "xdvi",
112         "XeTeX", N_("None"), ""
113 };
114
115
116 char const * const tex_fonts_roman[] =
117 {
118         "default", "cmr", "lmodern", "ae", "times", "palatino",
119         "charter", "newcent", "bookman", "utopia", "beraserif",
120         "ccfonts", "chancery", ""
121 };
122
123
124 char const * tex_fonts_roman_gui[] =
125 {
126         N_("Default"), N_("Computer Modern Roman"), N_("Latin Modern Roman"),
127         N_("AE (Almost European)"), N_("Times Roman"), N_("Palatino"),
128         N_("Bitstream Charter"), N_("New Century Schoolbook"), N_("Bookman"),
129         N_("Utopia"),  N_("Bera Serif"), N_("Concrete Roman"), N_("Zapf Chancery"),
130         ""
131 };
132
133
134 char const * const tex_fonts_sans[] =
135 {
136         "default", "cmss", "lmss", "helvet", "avant", "berasans", "cmbr", ""
137 };
138
139
140 char const * tex_fonts_sans_gui[] =
141 {
142         N_("Default"), N_("Computer Modern Sans"), N_("Latin Modern Sans"),
143         N_("Helvetica"), N_("Avant Garde"), N_("Bera Sans"), N_("CM Bright"), ""
144 };
145
146
147 char const * const tex_fonts_monospaced[] =
148 {
149         "default", "cmtt", "lmtt", "courier", "beramono", "luximono", "cmtl", ""
150 };
151
152
153 char const * tex_fonts_monospaced_gui[] =
154 {
155         N_("Default"), N_("Computer Modern Typewriter"),
156         N_("Latin Modern Typewriter"), N_("Courier"), N_("Bera Mono"),
157         N_("LuxiMono"), N_("CM Typewriter Light"), ""
158 };
159
160
161 char const * backref_opts[] =
162 {
163         "false", "section", "slide", "page", ""
164 };
165
166
167 char const * backref_opts_gui[] =
168 {
169         N_("Off"), N_("Section"), N_("Slide"), N_("Page"), ""
170 };
171
172
173 vector<pair<string, QString> > pagestyles;
174
175
176 } // anonymous namespace
177
178 namespace lyx {
179
180 RGBColor set_backgroundcolor;
181
182 namespace {
183 // used when sorting the textclass list.
184 class less_textclass_avail_desc
185         : public binary_function<string, string, int>
186 {
187 public:
188         bool operator()(string const & lhs, string const & rhs) const
189         {
190                 // Ordering criteria:
191                 //   1. Availability of text class
192                 //   2. Description (lexicographic)
193                 LayoutFile const & tc1 = LayoutFileList::get()[lhs];
194                 LayoutFile const & tc2 = LayoutFileList::get()[rhs];
195                 int const order = compare_no_case(
196                         translateIfPossible(from_utf8(tc1.description())),
197                         translateIfPossible(from_utf8(tc2.description())));
198                 return (tc1.isTeXClassAvailable() && !tc2.isTeXClassAvailable()) ||
199                         (tc1.isTeXClassAvailable() == tc2.isTeXClassAvailable() && order < 0);
200         }
201 };
202
203 }
204
205 namespace frontend {
206 namespace {
207
208 vector<string> getRequiredList(string const & modName) 
209 {
210         LyXModule const * const mod = theModuleList[modName];
211         if (!mod)
212                 return vector<string>(); //empty such thing
213         return mod->getRequiredModules();
214 }
215
216
217 vector<string> getExcludedList(string const & modName)
218 {
219         LyXModule const * const mod = theModuleList[modName];
220         if (!mod)
221                 return vector<string>(); //empty such thing
222         return mod->getExcludedModules();
223 }
224
225
226 docstring getModuleDescription(string const & modName)
227 {
228         LyXModule const * const mod = theModuleList[modName];
229         if (!mod)
230                 return _("Module not found!");
231         // FIXME Unicode
232         return translateIfPossible(from_utf8(mod->getDescription()));
233 }
234
235
236 vector<string> getPackageList(string const & modName)
237 {
238         LyXModule const * const mod = theModuleList[modName];
239         if (!mod)
240                 return vector<string>(); //empty such thing
241         return mod->getPackageList();
242 }
243
244
245 bool isModuleAvailable(string const & modName)
246 {
247         LyXModule const * const mod = theModuleList[modName];
248         if (!mod)
249                 return false;
250         return mod->isAvailable();
251 }
252
253 } // anonymous namespace
254
255
256 /////////////////////////////////////////////////////////////////////
257 //
258 // ModuleSelectionManager
259 //
260 /////////////////////////////////////////////////////////////////////
261
262 /// SelectionManager for use with modules
263 class ModuleSelectionManager : public GuiSelectionManager 
264 {
265 public:
266         ///
267         ModuleSelectionManager(
268                 QTreeView * availableLV,
269                 QListView * selectedLV,
270                 QPushButton * addPB, 
271                 QPushButton * delPB, 
272                 QPushButton * upPB, 
273                 QPushButton * downPB,
274                 GuiIdListModel * availableModel,
275                 GuiIdListModel * selectedModel,
276                 GuiDocument const * container)
277         : GuiSelectionManager(availableLV, selectedLV, addPB, delPB,
278                                 upPB, downPB, availableModel, selectedModel), container_(container)
279                 {}
280         ///
281         void updateProvidedModules(LayoutModuleList const & pm) 
282                         { provided_modules_ = pm.list(); }
283         ///
284         void updateExcludedModules(LayoutModuleList const & em) 
285                         { excluded_modules_ = em.list(); }
286 private:
287         ///
288         virtual void updateAddPB();
289         ///
290         virtual void updateUpPB();
291         ///
292         virtual void updateDownPB();
293         ///
294         virtual void updateDelPB();
295         /// returns availableModel as a GuiIdListModel
296         GuiIdListModel * getAvailableModel() 
297         {
298                 return dynamic_cast<GuiIdListModel *>(availableModel);
299         }
300         /// returns selectedModel as a GuiIdListModel
301         GuiIdListModel * getSelectedModel() 
302         {
303                 return dynamic_cast<GuiIdListModel *>(selectedModel);
304         }
305         /// keeps a list of the modules the text class provides
306         list<string> provided_modules_;
307         /// similarly...
308         list<string> excluded_modules_;
309         /// 
310         GuiDocument const * container_;
311 };
312
313 void ModuleSelectionManager::updateAddPB() 
314 {
315         int const arows = availableModel->rowCount();
316         QModelIndexList const avail_sels = 
317                         availableLV->selectionModel()->selectedIndexes();
318
319         // disable if there aren't any modules (?), if none of them is chosen
320         // in the dialog, or if the chosen one is already selected for use.
321         if (arows == 0 || avail_sels.isEmpty() || isSelected(avail_sels.first())) {
322                 addPB->setEnabled(false);
323                 return;
324         }
325
326         QModelIndex const & idx = availableLV->selectionModel()->currentIndex();
327         string const modname = getAvailableModel()->getIDString(idx.row());
328
329         bool const enable = 
330                 container_->params().moduleCanBeAdded(modname);
331         addPB->setEnabled(enable);
332 }
333
334
335 void ModuleSelectionManager::updateDownPB()
336 {
337         int const srows = selectedModel->rowCount();
338         if (srows == 0) {
339                 downPB->setEnabled(false);
340                 return;
341         }
342         QModelIndex const & curidx = selectedLV->selectionModel()->currentIndex();
343         int const curRow = curidx.row();
344         if (curRow < 0 || curRow >= srows - 1) { // invalid or last item
345                 downPB->setEnabled(false);
346                 return;
347         }
348
349         // determine whether immediately succeding element requires this one
350         string const curmodname = getSelectedModel()->getIDString(curRow);
351         string const nextmodname = getSelectedModel()->getIDString(curRow + 1);
352
353         vector<string> reqs = getRequiredList(nextmodname);
354
355         // if it doesn't require anything....
356         if (reqs.empty()) {
357                 downPB->setEnabled(true);
358                 return;
359         }
360
361         // Enable it if this module isn't required.
362         // FIXME This should perhaps be more flexible and check whether, even 
363         // if the next one is required, there is also an earlier one that will do.
364         downPB->setEnabled(
365                         find(reqs.begin(), reqs.end(), curmodname) == reqs.end());
366 }
367
368 void ModuleSelectionManager::updateUpPB() 
369 {
370         int const srows = selectedModel->rowCount();
371         if (srows == 0) {
372                 upPB->setEnabled(false);
373                 return;
374         }
375
376         QModelIndex const & curIdx = selectedLV->selectionModel()->currentIndex();
377         int curRow = curIdx.row();
378         if (curRow <= 0 || curRow > srows - 1) { // first item or invalid
379                 upPB->setEnabled(false);
380                 return;
381         }
382         string const curmodname = getSelectedModel()->getIDString(curRow);
383
384         // determine whether immediately preceding element is required by this one
385         vector<string> reqs = getRequiredList(curmodname);
386
387         // if this one doesn't require anything....
388         if (reqs.empty()) {
389                 upPB->setEnabled(true);
390                 return;
391         }
392
393
394         // Enable it if the preceding module isn't required.
395         // NOTE This is less flexible than it might be. We could check whether, even 
396         // if the previous one is required, there is an earlier one that would do.
397         string const premod = getSelectedModel()->getIDString(curRow - 1);
398         upPB->setEnabled(find(reqs.begin(), reqs.end(), premod) == reqs.end());
399 }
400
401 void ModuleSelectionManager::updateDelPB() 
402 {
403         int const srows = selectedModel->rowCount();
404         if (srows == 0) {
405                 deletePB->setEnabled(false);
406                 return;
407         }
408
409         QModelIndex const & curidx = 
410                 selectedLV->selectionModel()->currentIndex();
411         int const curRow = curidx.row();
412         if (curRow < 0 || curRow >= srows) { // invalid index?
413                 deletePB->setEnabled(false);
414                 return;
415         }
416
417         string const curmodname = getSelectedModel()->getIDString(curRow);
418
419         // We're looking here for a reason NOT to enable the button. If we
420         // find one, we disable it and return. If we don't, we'll end up at
421         // the end of the function, and then we enable it.
422         for (int i = curRow + 1; i < srows; ++i) {
423                 string const thisMod = getSelectedModel()->getIDString(i);
424                 vector<string> reqs = getRequiredList(thisMod);
425                 //does this one require us?
426                 if (find(reqs.begin(), reqs.end(), curmodname) == reqs.end())
427                         //no...
428                         continue;
429
430                 // OK, so this module requires us
431                 // is there an EARLIER module that also satisfies the require?
432                 // NOTE We demand that it be earlier to keep the list of modules
433                 // consistent with the rule that a module must be proceeded by a
434                 // required module. There would be more flexible ways to proceed,
435                 // but that would be a lot more complicated, and the logic here is
436                 // already complicated. (That's why I've left the debugging code.)
437                 // lyxerr << "Testing " << thisMod << endl;
438                 bool foundone = false;
439                 for (int j = 0; j < curRow; ++j) {
440                         string const mod = getSelectedModel()->getIDString(j);
441                         // lyxerr << "In loop: Testing " << mod << endl;
442                         // do we satisfy the require? 
443                         if (find(reqs.begin(), reqs.end(), mod) != reqs.end()) {
444                                 // lyxerr << mod << " does the trick." << endl;
445                                 foundone = true;
446                                 break;
447                         }
448                 }
449                 // did we find a module to satisfy the require?
450                 if (!foundone) {
451                         // lyxerr << "No matching module found." << endl;
452                         deletePB->setEnabled(false);
453                         return;
454                 }
455         }
456         // lyxerr << "All's well that ends well." << endl;
457         deletePB->setEnabled(true);
458 }
459
460
461 /////////////////////////////////////////////////////////////////////
462 //
463 // PreambleModule
464 //
465 /////////////////////////////////////////////////////////////////////
466
467 PreambleModule::PreambleModule() : current_id_(0)
468 {
469         // This is not a memory leak. The object will be destroyed
470         // with this.
471         (void) new LaTeXHighlighter(preambleTE->document());
472         setFocusProxy(preambleTE);
473         connect(preambleTE, SIGNAL(textChanged()), this, SIGNAL(changed()));
474 }
475
476
477 void PreambleModule::update(BufferParams const & params, BufferId id)
478 {
479         QString preamble = toqstr(params.preamble);
480         // Nothing to do if the params and preamble are unchanged.
481         if (id == current_id_
482                 && preamble == preambleTE->document()->toPlainText())
483                 return;
484
485         QTextCursor cur = preambleTE->textCursor();
486         // Save the coords before switching to the new one.
487         preamble_coords_[current_id_] =
488                 make_pair(cur.position(), preambleTE->verticalScrollBar()->value());
489
490         // Save the params address for further use.
491         current_id_ = id;
492         preambleTE->document()->setPlainText(preamble);
493         Coords::const_iterator it = preamble_coords_.find(current_id_);
494         if (it == preamble_coords_.end())
495                 // First time we open this one.
496                 preamble_coords_[current_id_] = make_pair(0, 0);
497         else {
498                 // Restore saved coords.
499                 QTextCursor cur = preambleTE->textCursor();
500                 cur.setPosition(it->second.first);
501                 preambleTE->setTextCursor(cur);
502                 preambleTE->verticalScrollBar()->setValue(it->second.second);
503         }
504 }
505
506
507 void PreambleModule::apply(BufferParams & params)
508 {
509         params.preamble = fromqstr(preambleTE->document()->toPlainText());
510 }
511
512
513 void PreambleModule::closeEvent(QCloseEvent * e)
514 {
515         // Save the coords before closing.
516         QTextCursor cur = preambleTE->textCursor();
517         preamble_coords_[current_id_] =
518                 make_pair(cur.position(), preambleTE->verticalScrollBar()->value());
519         e->accept();
520 }
521
522
523 /////////////////////////////////////////////////////////////////////
524 //
525 // DocumentDialog
526 //
527 /////////////////////////////////////////////////////////////////////
528
529
530 GuiDocument::GuiDocument(GuiView & lv)
531         : GuiDialog(lv, "document", qt_("Document Settings"))
532 {
533         setupUi(this);
534
535         connect(okPB, SIGNAL(clicked()), this, SLOT(slotOK()));
536         connect(applyPB, SIGNAL(clicked()), this, SLOT(slotApply()));
537         connect(closePB, SIGNAL(clicked()), this, SLOT(slotClose()));
538         connect(restorePB, SIGNAL(clicked()), this, SLOT(slotRestore()));
539
540         connect(savePB, SIGNAL(clicked()), this, SLOT(saveDefaultClicked()));
541         connect(defaultPB, SIGNAL(clicked()), this, SLOT(useDefaultsClicked()));
542
543         // Manage the restore, ok, apply, restore and cancel/close buttons
544         bc().setPolicy(ButtonPolicy::NoRepeatedApplyReadOnlyPolicy);
545         bc().setOK(okPB);
546         bc().setApply(applyPB);
547         bc().setCancel(closePB);
548         bc().setRestore(restorePB);
549
550         textLayoutModule = new UiWidget<Ui::TextLayoutUi>;
551         // text layout
552         connect(textLayoutModule->lspacingCO, SIGNAL(activated(int)),
553                 this, SLOT(change_adaptor()));
554         connect(textLayoutModule->lspacingCO, SIGNAL(activated(int)),
555                 this, SLOT(setLSpacing(int)));
556         connect(textLayoutModule->lspacingLE, SIGNAL(textChanged(const QString &)),
557                 this, SLOT(change_adaptor()));
558
559         connect(textLayoutModule->indentRB, SIGNAL(clicked()),
560                 this, SLOT(change_adaptor()));
561         connect(textLayoutModule->indentRB, SIGNAL(toggled(bool)),
562                 textLayoutModule->indentCO, SLOT(setEnabled(bool)));
563         connect(textLayoutModule->indentCO, SIGNAL(activated(int)),
564                 this, SLOT(change_adaptor()));
565         connect(textLayoutModule->indentCO, SIGNAL(activated(int)),
566                 this, SLOT(setIndent(int)));
567         connect(textLayoutModule->indentLE, SIGNAL(textChanged(const QString &)),
568                 this, SLOT(change_adaptor()));
569         connect(textLayoutModule->indentLengthCO, SIGNAL(activated(int)),
570                 this, SLOT(change_adaptor()));
571
572         connect(textLayoutModule->skipRB, SIGNAL(clicked()),
573                 this, SLOT(change_adaptor()));
574         connect(textLayoutModule->skipRB, SIGNAL(toggled(bool)),
575                 textLayoutModule->skipCO, SLOT(setEnabled(bool)));
576         connect(textLayoutModule->skipCO, SIGNAL(activated(int)),
577                 this, SLOT(change_adaptor()));
578         connect(textLayoutModule->skipCO, SIGNAL(activated(int)),
579                 this, SLOT(setSkip(int)));
580         connect(textLayoutModule->skipLE, SIGNAL(textChanged(const QString &)),
581                 this, SLOT(change_adaptor()));
582         connect(textLayoutModule->skipLengthCO, SIGNAL(activated(int)),
583                 this, SLOT(change_adaptor()));
584
585         connect(textLayoutModule->indentRB, SIGNAL(toggled(bool)),
586                 this, SLOT(enableIndent(bool)));
587         connect(textLayoutModule->skipRB, SIGNAL(toggled(bool)),
588                 this, SLOT(enableSkip(bool)));
589
590         connect(textLayoutModule->twoColumnCB, SIGNAL(clicked()),
591                 this, SLOT(change_adaptor()));
592         connect(textLayoutModule->twoColumnCB, SIGNAL(clicked()),
593                 this, SLOT(setColSep()));
594
595         textLayoutModule->lspacingLE->setValidator(new QDoubleValidator(
596                 textLayoutModule->lspacingLE));
597         textLayoutModule->indentLE->setValidator(unsignedLengthValidator(
598                 textLayoutModule->indentLE));
599         textLayoutModule->skipLE->setValidator(unsignedGlueLengthValidator(
600                 textLayoutModule->skipLE));
601
602         textLayoutModule->indentCO->addItem(qt_("Default"));
603         textLayoutModule->indentCO->addItem(qt_("Custom"));
604         textLayoutModule->skipCO->addItem(qt_("SmallSkip"));
605         textLayoutModule->skipCO->addItem(qt_("MedSkip"));
606         textLayoutModule->skipCO->addItem(qt_("BigSkip"));
607         textLayoutModule->skipCO->addItem(qt_("Custom"));
608         textLayoutModule->lspacingCO->insertItem(
609                 Spacing::Single, qt_("Single"));
610         textLayoutModule->lspacingCO->insertItem(
611                 Spacing::Onehalf, qt_("OneHalf"));
612         textLayoutModule->lspacingCO->insertItem(
613                 Spacing::Double, qt_("Double"));
614         textLayoutModule->lspacingCO->insertItem(
615                 Spacing::Other, qt_("Custom"));
616         // initialize the length validator
617         bc().addCheckedLineEdit(textLayoutModule->indentLE);
618         bc().addCheckedLineEdit(textLayoutModule->skipLE);
619
620         // master/child handling
621         masterChildModule = new UiWidget<Ui::MasterChildUi>;
622
623         connect(masterChildModule->childrenTW, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
624                 this, SLOT(includeonlyClicked(QTreeWidgetItem *, int)));
625         connect(masterChildModule->includeonlyRB, SIGNAL(toggled(bool)),
626                 masterChildModule->childrenTW, SLOT(setEnabled(bool)));
627         connect(masterChildModule->includeonlyRB, SIGNAL(toggled(bool)),
628                 masterChildModule->maintainAuxCB, SLOT(setEnabled(bool)));
629         connect(masterChildModule->includeallRB, SIGNAL(clicked()),
630                 this, SLOT(change_adaptor()));
631         connect(masterChildModule->includeonlyRB, SIGNAL(clicked()),
632                 this, SLOT(change_adaptor()));
633         connect(masterChildModule->maintainAuxCB, SIGNAL(clicked()),
634                 this, SLOT(change_adaptor()));
635         masterChildModule->childrenTW->setColumnCount(2);
636         masterChildModule->childrenTW->headerItem()->setText(0, qt_("Child Document"));
637         masterChildModule->childrenTW->headerItem()->setText(1, qt_("Include to Output"));
638         masterChildModule->childrenTW->resizeColumnToContents(1);
639         masterChildModule->childrenTW->resizeColumnToContents(2);
640
641         // output
642         outputModule = new UiWidget<Ui::OutputUi>;
643
644         connect(outputModule->xetexCB, SIGNAL(clicked()),
645                 this, SLOT(change_adaptor()));
646         connect(outputModule->xetexCB, SIGNAL(toggled(bool)),
647                 this, SLOT(xetexChanged(bool)));
648         connect(outputModule->defaultFormatCO, SIGNAL(activated(int)),
649                 this, SLOT(change_adaptor()));
650
651         // fonts
652         fontModule = new UiWidget<Ui::FontUi>;
653         connect(fontModule->fontsRomanCO, SIGNAL(activated(int)),
654                 this, SLOT(change_adaptor()));
655         connect(fontModule->fontsRomanCO, SIGNAL(activated(int)),
656                 this, SLOT(romanChanged(int)));
657         connect(fontModule->fontsSansCO, SIGNAL(activated(int)),
658                 this, SLOT(change_adaptor()));
659         connect(fontModule->fontsSansCO, SIGNAL(activated(int)),
660                 this, SLOT(sansChanged(int)));
661         connect(fontModule->fontsTypewriterCO, SIGNAL(activated(int)),
662                 this, SLOT(change_adaptor()));
663         connect(fontModule->fontsTypewriterCO, SIGNAL(activated(int)),
664                 this, SLOT(ttChanged(int)));
665         connect(fontModule->fontsDefaultCO, SIGNAL(activated(int)),
666                 this, SLOT(change_adaptor()));
667         connect(fontModule->fontencCO, SIGNAL(activated(int)),
668                 this, SLOT(change_adaptor()));
669         connect(fontModule->fontencCO, SIGNAL(activated(int)),
670                 this, SLOT(fontencChanged(int)));
671         connect(fontModule->fontencLE, SIGNAL(textChanged(const QString &)),
672                 this, SLOT(change_adaptor()));
673         connect(fontModule->fontsizeCO, SIGNAL(activated(int)),
674                 this, SLOT(change_adaptor()));
675         connect(fontModule->cjkFontLE, SIGNAL(textChanged(const QString &)),
676                 this, SLOT(change_adaptor()));
677         connect(fontModule->scaleSansSB, SIGNAL(valueChanged(int)),
678                 this, SLOT(change_adaptor()));
679         connect(fontModule->scaleTypewriterSB, SIGNAL(valueChanged(int)),
680                 this, SLOT(change_adaptor()));
681         connect(fontModule->fontScCB, SIGNAL(clicked()),
682                 this, SLOT(change_adaptor()));
683         connect(fontModule->fontOsfCB, SIGNAL(clicked()),
684                 this, SLOT(change_adaptor()));
685
686         updateFontlist();
687
688         fontModule->fontsizeCO->addItem(qt_("Default"));
689         fontModule->fontsizeCO->addItem(qt_("10"));
690         fontModule->fontsizeCO->addItem(qt_("11"));
691         fontModule->fontsizeCO->addItem(qt_("12"));
692
693         fontModule->fontencCO->addItem(qt_("Default"));
694         fontModule->fontencCO->addItem(qt_("Custom"));
695         fontModule->fontencCO->addItem(qt_("None (no fontenc)"));
696
697         for (int n = 0; GuiDocument::fontfamilies_gui[n][0]; ++n)
698                 fontModule->fontsDefaultCO->addItem(
699                         qt_(GuiDocument::fontfamilies_gui[n]));
700
701
702         pageLayoutModule = new UiWidget<Ui::PageLayoutUi>;
703         // page layout
704         connect(pageLayoutModule->papersizeCO, SIGNAL(activated(int)),
705                 this, SLOT(papersizeChanged(int)));
706         connect(pageLayoutModule->papersizeCO, SIGNAL(activated(int)),
707                 this, SLOT(papersizeChanged(int)));
708         connect(pageLayoutModule->portraitRB, SIGNAL(clicked()),
709                 this, SLOT(portraitChanged()));
710         connect(pageLayoutModule->papersizeCO, SIGNAL(activated(int)),
711                 this, SLOT(change_adaptor()));
712         connect(pageLayoutModule->paperheightLE, SIGNAL(textChanged(const QString &)),
713                 this, SLOT(change_adaptor()));
714         connect(pageLayoutModule->paperwidthLE, SIGNAL(textChanged(const QString &)),
715                 this, SLOT(change_adaptor()));
716         connect(pageLayoutModule->paperwidthUnitCO, SIGNAL(activated(int)),
717                 this, SLOT(change_adaptor()));
718         connect(pageLayoutModule->paperheightUnitCO, SIGNAL(activated(int)),
719                 this, SLOT(change_adaptor()));
720         connect(pageLayoutModule->portraitRB, SIGNAL(clicked()),
721                 this, SLOT(change_adaptor()));
722         connect(pageLayoutModule->landscapeRB, SIGNAL(clicked()),
723                 this, SLOT(change_adaptor()));
724         connect(pageLayoutModule->facingPagesCB, SIGNAL(clicked()),
725                 this, SLOT(change_adaptor()));
726         connect(pageLayoutModule->pagestyleCO, SIGNAL(activated(int)),
727                 this, SLOT(change_adaptor()));
728         connect(pageLayoutModule->backgroundPB, SIGNAL(clicked()),
729                 this, SLOT(changeBackgroundColor()));
730         connect(pageLayoutModule->delbackgroundTB, SIGNAL(clicked()),
731                 this, SLOT(deleteBackgroundColor()));
732
733         pageLayoutModule->pagestyleCO->addItem(qt_("Default"));
734         pageLayoutModule->pagestyleCO->addItem(qt_("empty"));
735         pageLayoutModule->pagestyleCO->addItem(qt_("plain"));
736         pageLayoutModule->pagestyleCO->addItem(qt_("headings"));
737         pageLayoutModule->pagestyleCO->addItem(qt_("fancy"));
738         bc().addCheckedLineEdit(pageLayoutModule->paperheightLE,
739                 pageLayoutModule->paperheightL);
740         bc().addCheckedLineEdit(pageLayoutModule->paperwidthLE,
741                 pageLayoutModule->paperwidthL);
742
743         // paper
744         QComboBox * cb = pageLayoutModule->papersizeCO;
745         cb->addItem(qt_("Default"));
746         cb->addItem(qt_("Custom"));
747         cb->addItem(qt_("US letter"));
748         cb->addItem(qt_("US legal"));
749         cb->addItem(qt_("US executive"));
750         cb->addItem(qt_("A3"));
751         cb->addItem(qt_("A4"));
752         cb->addItem(qt_("A5"));
753         cb->addItem(qt_("B3"));
754         cb->addItem(qt_("B4"));
755         cb->addItem(qt_("B5"));
756         // remove the %-items from the unit choice
757         pageLayoutModule->paperwidthUnitCO->noPercents();
758         pageLayoutModule->paperheightUnitCO->noPercents();
759         pageLayoutModule->paperheightLE->setValidator(unsignedLengthValidator(
760                 pageLayoutModule->paperheightLE));
761         pageLayoutModule->paperwidthLE->setValidator(unsignedLengthValidator(
762                 pageLayoutModule->paperwidthLE));
763
764
765         marginsModule = new UiWidget<Ui::MarginsUi>;
766         // margins
767         connect(marginsModule->marginCB, SIGNAL(toggled(bool)),
768                 this, SLOT(setCustomMargins(bool)));
769         connect(marginsModule->marginCB, SIGNAL(clicked()),
770                 this, SLOT(change_adaptor()));
771         connect(marginsModule->topLE, SIGNAL(textChanged(QString)),
772                 this, SLOT(change_adaptor()));
773         connect(marginsModule->topUnit, SIGNAL(activated(int)),
774                 this, SLOT(change_adaptor()));
775         connect(marginsModule->bottomLE, SIGNAL(textChanged(QString)),
776                 this, SLOT(change_adaptor()));
777         connect(marginsModule->bottomUnit, SIGNAL(activated(int)),
778                 this, SLOT(change_adaptor()));
779         connect(marginsModule->innerLE, SIGNAL(textChanged(QString)),
780                 this, SLOT(change_adaptor()));
781         connect(marginsModule->innerUnit, SIGNAL(activated(int)),
782                 this, SLOT(change_adaptor()));
783         connect(marginsModule->outerLE, SIGNAL(textChanged(QString)),
784                 this, SLOT(change_adaptor()));
785         connect(marginsModule->outerUnit, SIGNAL(activated(int)),
786                 this, SLOT(change_adaptor()));
787         connect(marginsModule->headheightLE, SIGNAL(textChanged(QString)),
788                 this, SLOT(change_adaptor()));
789         connect(marginsModule->headheightUnit, SIGNAL(activated(int)),
790                 this, SLOT(change_adaptor()));
791         connect(marginsModule->headsepLE, SIGNAL(textChanged(QString)),
792                 this, SLOT(change_adaptor()));
793         connect(marginsModule->headsepUnit, SIGNAL(activated(int)),
794                 this, SLOT(change_adaptor()));
795         connect(marginsModule->footskipLE, SIGNAL(textChanged(QString)),
796                 this, SLOT(change_adaptor()));
797         connect(marginsModule->footskipUnit, SIGNAL(activated(int)),
798                 this, SLOT(change_adaptor()));
799         connect(marginsModule->columnsepLE, SIGNAL(textChanged(QString)),
800                 this, SLOT(change_adaptor()));
801         connect(marginsModule->columnsepUnit, SIGNAL(activated(int)),
802                 this, SLOT(change_adaptor()));
803         marginsModule->topLE->setValidator(unsignedLengthValidator(
804                 marginsModule->topLE));
805         marginsModule->bottomLE->setValidator(unsignedLengthValidator(
806                 marginsModule->bottomLE));
807         marginsModule->innerLE->setValidator(unsignedLengthValidator(
808                 marginsModule->innerLE));
809         marginsModule->outerLE->setValidator(unsignedLengthValidator(
810                 marginsModule->outerLE));
811         marginsModule->headsepLE->setValidator(unsignedLengthValidator(
812                 marginsModule->headsepLE));
813         marginsModule->headheightLE->setValidator(unsignedLengthValidator(
814                 marginsModule->headheightLE));
815         marginsModule->footskipLE->setValidator(unsignedLengthValidator(
816                 marginsModule->footskipLE));
817         marginsModule->columnsepLE->setValidator(unsignedLengthValidator(
818                 marginsModule->columnsepLE));
819
820         bc().addCheckedLineEdit(marginsModule->topLE,
821                 marginsModule->topL);
822         bc().addCheckedLineEdit(marginsModule->bottomLE,
823                 marginsModule->bottomL);
824         bc().addCheckedLineEdit(marginsModule->innerLE,
825                 marginsModule->innerL);
826         bc().addCheckedLineEdit(marginsModule->outerLE,
827                 marginsModule->outerL);
828         bc().addCheckedLineEdit(marginsModule->headsepLE,
829                 marginsModule->headsepL);
830         bc().addCheckedLineEdit(marginsModule->headheightLE,
831                 marginsModule->headheightL);
832         bc().addCheckedLineEdit(marginsModule->footskipLE,
833                 marginsModule->footskipL);
834         bc().addCheckedLineEdit(marginsModule->columnsepLE,
835                 marginsModule->columnsepL);
836
837
838         langModule = new UiWidget<Ui::LanguageUi>;
839         // language & quote
840         connect(langModule->languageCO, SIGNAL(activated(int)),
841                 this, SLOT(change_adaptor()));
842         connect(langModule->defaultencodingRB, SIGNAL(clicked()),
843                 this, SLOT(change_adaptor()));
844         connect(langModule->otherencodingRB, SIGNAL(clicked()),
845                 this, SLOT(change_adaptor()));
846         connect(langModule->encodingCO, SIGNAL(activated(int)),
847                 this, SLOT(change_adaptor()));
848         connect(langModule->quoteStyleCO, SIGNAL(activated(int)),
849                 this, SLOT(change_adaptor()));
850         // language & quotes
851         QAbstractItemModel * language_model = guiApp->languageModel();
852         // FIXME: it would be nice if sorting was enabled/disabled via a checkbox.
853         language_model->sort(0);
854         langModule->languageCO->setModel(language_model);
855
856         // Always put the default encoding in the first position.
857         langModule->encodingCO->addItem(qt_("Language Default (no inputenc)"));
858         QStringList encodinglist;
859         Encodings::const_iterator it = encodings.begin();
860         Encodings::const_iterator const end = encodings.end();
861         for (; it != end; ++it)
862                 encodinglist.append(qt_(it->guiName()));
863         encodinglist.sort();
864         langModule->encodingCO->addItems(encodinglist);
865
866         langModule->quoteStyleCO->addItem(qt_("``text''"));
867         langModule->quoteStyleCO->addItem(qt_("''text''"));
868         langModule->quoteStyleCO->addItem(qt_(",,text``"));
869         langModule->quoteStyleCO->addItem(qt_(",,text''"));
870         langModule->quoteStyleCO->addItem(qt_("<<text>>"));
871         langModule->quoteStyleCO->addItem(qt_(">>text<<"));
872
873
874         numberingModule = new UiWidget<Ui::NumberingUi>;
875         // numbering
876         connect(numberingModule->depthSL, SIGNAL(valueChanged(int)),
877                 this, SLOT(change_adaptor()));
878         connect(numberingModule->tocSL, SIGNAL(valueChanged(int)),
879                 this, SLOT(change_adaptor()));
880         connect(numberingModule->depthSL, SIGNAL(valueChanged(int)),
881                 this, SLOT(updateNumbering()));
882         connect(numberingModule->tocSL, SIGNAL(valueChanged(int)),
883                 this, SLOT(updateNumbering()));
884         numberingModule->tocTW->setColumnCount(3);
885         numberingModule->tocTW->headerItem()->setText(0, qt_("Example"));
886         numberingModule->tocTW->headerItem()->setText(1, qt_("Numbered"));
887         numberingModule->tocTW->headerItem()->setText(2, qt_("Appears in TOC"));
888
889
890         biblioModule = new UiWidget<Ui::BiblioUi>;
891         connect(biblioModule->citeNatbibRB, SIGNAL(toggled(bool)),
892                 biblioModule->citationStyleL, SLOT(setEnabled(bool)));
893         connect(biblioModule->citeNatbibRB, SIGNAL(toggled(bool)),
894                 biblioModule->citeStyleCO, SLOT(setEnabled(bool)));
895         // biblio
896         connect(biblioModule->citeDefaultRB, SIGNAL(clicked()),
897                 this, SLOT(change_adaptor()));
898         connect(biblioModule->citeNatbibRB, SIGNAL(clicked()),
899                 this, SLOT(change_adaptor()));
900         connect(biblioModule->citeStyleCO, SIGNAL(activated(int)),
901                 this, SLOT(change_adaptor()));
902         connect(biblioModule->citeJurabibRB, SIGNAL(clicked()),
903                 this, SLOT(change_adaptor()));
904         connect(biblioModule->bibtopicCB, SIGNAL(clicked()),
905                 this, SLOT(change_adaptor()));
906         connect(biblioModule->bibtexCO, SIGNAL(activated(int)),
907                 this, SLOT(bibtexChanged(int)));
908         connect(biblioModule->bibtexOptionsED, SIGNAL(textChanged(QString)),
909                 this, SLOT(change_adaptor()));
910         // biblio
911         biblioModule->citeStyleCO->addItem(qt_("Author-year"));
912         biblioModule->citeStyleCO->addItem(qt_("Numerical"));
913         biblioModule->citeStyleCO->setCurrentIndex(0);
914         
915         biblioModule->bibtexCO->clear();
916
917         biblioModule->bibtexCO->addItem(qt_("Default"), QString("default"));
918         for (set<string>::const_iterator it = lyxrc.bibtex_alternatives.begin();
919                              it != lyxrc.bibtex_alternatives.end(); ++it) {
920                 QString const command = toqstr(*it).left(toqstr(*it).indexOf(" "));
921                 biblioModule->bibtexCO->addItem(command, command);
922         }
923
924         // indices
925         indicesModule = new GuiIndices;
926         connect(indicesModule, SIGNAL(changed()),
927                 this, SLOT(change_adaptor()));
928
929
930         mathsModule = new UiWidget<Ui::MathsUi>;
931         connect(mathsModule->amsautoCB, SIGNAL(toggled(bool)),
932                 mathsModule->amsCB, SLOT(setDisabled(bool)));
933         connect(mathsModule->esintautoCB, SIGNAL(toggled(bool)),
934                 mathsModule->esintCB, SLOT(setDisabled(bool)));
935         connect(mathsModule->mhchemautoCB, SIGNAL(toggled(bool)),
936                 mathsModule->mhchemCB, SLOT(setDisabled(bool)));
937         // maths
938         connect(mathsModule->amsCB, SIGNAL(clicked()),
939                 this, SLOT(change_adaptor()));
940         connect(mathsModule->amsautoCB, SIGNAL(clicked()),
941                 this, SLOT(change_adaptor()));
942         connect(mathsModule->esintCB, SIGNAL(clicked()),
943                 this, SLOT(change_adaptor()));
944         connect(mathsModule->esintautoCB, SIGNAL(clicked()),
945                 this, SLOT(change_adaptor()));
946         connect(mathsModule->mhchemCB, SIGNAL(clicked()),
947                 this, SLOT(change_adaptor()));
948         connect(mathsModule->mhchemautoCB, SIGNAL(clicked()),
949                 this, SLOT(change_adaptor()));
950
951         latexModule = new UiWidget<Ui::LaTeXUi>;
952         // latex class
953         connect(latexModule->optionsLE, SIGNAL(textChanged(QString)),
954                 this, SLOT(change_adaptor()));
955         connect(latexModule->defaultOptionsCB, SIGNAL(clicked()),
956                 this, SLOT(change_adaptor()));
957         connect(latexModule->psdriverCO, SIGNAL(activated(int)),
958                 this, SLOT(change_adaptor()));
959         connect(latexModule->classCO, SIGNAL(activated(int)),
960                 this, SLOT(classChanged()));
961         connect(latexModule->classCO, SIGNAL(activated(int)),
962                 this, SLOT(change_adaptor()));
963         connect(latexModule->layoutPB, SIGNAL(clicked()),
964                 this, SLOT(browseLayout()));
965         connect(latexModule->layoutPB, SIGNAL(clicked()),
966                 this, SLOT(change_adaptor()));
967         connect(latexModule->childDocGB, SIGNAL(clicked()),
968                 this, SLOT(change_adaptor()));
969         connect(latexModule->childDocLE, SIGNAL(textChanged(QString)),
970                 this, SLOT(change_adaptor()));
971         connect(latexModule->childDocPB, SIGNAL(clicked()),
972                 this, SLOT(browseMaster()));
973         connect(latexModule->suppressDateCB, SIGNAL(clicked()),
974                 this, SLOT(change_adaptor()));
975
976         // postscript drivers
977         for (int n = 0; tex_graphics[n][0]; ++n) {
978                 QString enc = qt_(tex_graphics_gui[n]);
979                 latexModule->psdriverCO->addItem(enc);
980         }
981         // latex classes
982         latexModule->classCO->setModel(&classes_model_);
983         LayoutFileList const & bcl = LayoutFileList::get();
984         vector<LayoutFileIndex> classList = bcl.classList();
985         sort(classList.begin(), classList.end(), less_textclass_avail_desc());
986
987         vector<LayoutFileIndex>::const_iterator cit  = classList.begin();
988         vector<LayoutFileIndex>::const_iterator cen = classList.end();
989         for (int i = 0; cit != cen; ++cit, ++i) {
990                 LayoutFile const & tc = bcl[*cit];
991                 docstring item = (tc.isTeXClassAvailable()) ?
992                         from_utf8(tc.description()) :
993                         bformat(_("Unavailable: %1$s"), from_utf8(tc.description()));
994                 classes_model_.insertRow(i, toqstr(item), *cit);
995         }
996
997         // branches
998         branchesModule = new GuiBranches;
999         connect(branchesModule, SIGNAL(changed()),
1000                 this, SLOT(change_adaptor()));
1001         connect(branchesModule, SIGNAL(renameBranches(docstring const &, docstring const &)),
1002                 this, SLOT(branchesRename(docstring const &, docstring const &)));
1003         updateUnknownBranches();
1004
1005         // preamble
1006         preambleModule = new PreambleModule;
1007         connect(preambleModule, SIGNAL(changed()),
1008                 this, SLOT(change_adaptor()));
1009
1010         // bullets
1011         bulletsModule = new BulletsModule;
1012         connect(bulletsModule, SIGNAL(changed()),
1013                 this, SLOT(change_adaptor()));
1014
1015         // Modules
1016         modulesModule = new UiWidget<Ui::ModulesUi>;
1017         modulesModule->availableLV->header()->setVisible(false);
1018         selectionManager =
1019                 new ModuleSelectionManager(modulesModule->availableLV,
1020                         modulesModule->selectedLV,
1021                         modulesModule->addPB, modulesModule->deletePB,
1022                         modulesModule->upPB, modulesModule->downPB,
1023                         availableModel(), selectedModel(), this);
1024         connect(selectionManager, SIGNAL(updateHook()),
1025                 this, SLOT(updateModuleInfo()));
1026         connect(selectionManager, SIGNAL(updateHook()),
1027                 this, SLOT(change_adaptor()));
1028         connect(selectionManager, SIGNAL(selectionChanged()),
1029                 this, SLOT(modulesChanged()));
1030
1031         // PDF support
1032         pdfSupportModule = new UiWidget<Ui::PDFSupportUi>;
1033
1034         connect(pdfSupportModule->use_hyperrefGB, SIGNAL(toggled(bool)),
1035                 this, SLOT(change_adaptor()));
1036         connect(pdfSupportModule->titleLE, SIGNAL(textChanged(QString)),
1037                 this, SLOT(change_adaptor()));
1038         connect(pdfSupportModule->authorLE, SIGNAL(textChanged(QString)),
1039                 this, SLOT(change_adaptor()));
1040         connect(pdfSupportModule->subjectLE, SIGNAL(textChanged(QString)),
1041                 this, SLOT(change_adaptor()));
1042         connect(pdfSupportModule->keywordsLE, SIGNAL(textChanged(QString)),
1043                 this, SLOT(change_adaptor()));
1044         connect(pdfSupportModule->bookmarksGB, SIGNAL(toggled(bool)),
1045                 this, SLOT(change_adaptor()));
1046         connect(pdfSupportModule->bookmarksnumberedCB, SIGNAL(toggled(bool)),
1047                 this, SLOT(change_adaptor()));
1048         connect(pdfSupportModule->bookmarksopenGB, SIGNAL(toggled(bool)),
1049                 this, SLOT(change_adaptor()));
1050         connect(pdfSupportModule->bookmarksopenlevelSB, SIGNAL(valueChanged(int)),
1051                 this, SLOT(change_adaptor()));
1052         connect(pdfSupportModule->breaklinksCB, SIGNAL(toggled(bool)),
1053                 this, SLOT(change_adaptor()));
1054         connect(pdfSupportModule->pdfborderCB, SIGNAL(toggled(bool)),
1055                 this, SLOT(change_adaptor()));
1056         connect(pdfSupportModule->colorlinksCB, SIGNAL(toggled(bool)),
1057                 this, SLOT(change_adaptor()));
1058         connect(pdfSupportModule->backrefCO, SIGNAL(activated(int)),
1059                 this, SLOT(change_adaptor()));
1060         connect(pdfSupportModule->pdfusetitleCB, SIGNAL(toggled(bool)),
1061                 this, SLOT(change_adaptor()));
1062         connect(pdfSupportModule->fullscreenCB, SIGNAL(toggled(bool)),
1063                 this, SLOT(change_adaptor()));
1064         connect(pdfSupportModule->optionsLE, SIGNAL(textChanged(QString)),
1065                 this, SLOT(change_adaptor()));
1066
1067         for (int i = 0; backref_opts[i][0]; ++i)
1068                 pdfSupportModule->backrefCO->addItem(qt_(backref_opts_gui[i]));
1069
1070         // float
1071         floatModule = new FloatPlacement;
1072         connect(floatModule, SIGNAL(changed()),
1073                 this, SLOT(change_adaptor()));
1074
1075         // listings
1076         listingsModule = new UiWidget<Ui::ListingsSettingsUi>;
1077         connect(listingsModule->listingsED, SIGNAL(textChanged()),
1078                 this, SLOT(change_adaptor()));
1079         connect(listingsModule->bypassCB, SIGNAL(clicked()), 
1080                 this, SLOT(change_adaptor()));
1081         connect(listingsModule->bypassCB, SIGNAL(clicked()), 
1082                 this, SLOT(setListingsMessage()));
1083         connect(listingsModule->listingsED, SIGNAL(textChanged()),
1084                 this, SLOT(setListingsMessage()));
1085         listingsModule->listingsTB->setPlainText(
1086                 qt_("Input listings parameters below. Enter ? for a list of parameters."));
1087
1088         docPS->addPanel(latexModule, qt_("Document Class"));
1089         docPS->addPanel(masterChildModule, qt_("Child Documents"));
1090         docPS->addPanel(modulesModule, qt_("Modules"));
1091         docPS->addPanel(fontModule, qt_("Fonts"));
1092         docPS->addPanel(textLayoutModule, qt_("Text Layout"));
1093         docPS->addPanel(pageLayoutModule, qt_("Page Layout"));
1094         docPS->addPanel(marginsModule, qt_("Page Margins"));
1095         docPS->addPanel(langModule, qt_("Language"));
1096         docPS->addPanel(numberingModule, qt_("Numbering & TOC"));
1097         docPS->addPanel(biblioModule, qt_("Bibliography"));
1098         docPS->addPanel(indicesModule, qt_("Indexes"));
1099         docPS->addPanel(pdfSupportModule, qt_("PDF Properties"));
1100         docPS->addPanel(mathsModule, qt_("Math Options"));
1101         docPS->addPanel(floatModule, qt_("Float Placement"));
1102         docPS->addPanel(listingsModule, qt_("Listings"));
1103         docPS->addPanel(bulletsModule, qt_("Bullets"));
1104         docPS->addPanel(branchesModule, qt_("Branches"));
1105         docPS->addPanel(outputModule, qt_("Output"));
1106         docPS->addPanel(preambleModule, qt_("LaTeX Preamble"));
1107         docPS->setCurrentPanel(qt_("Document Class"));
1108 // FIXME: hack to work around resizing bug in Qt >= 4.2
1109 // bug verified with Qt 4.2.{0-3} (JSpitzm)
1110 #if QT_VERSION >= 0x040200
1111         docPS->updateGeometry();
1112 #endif
1113 }
1114
1115
1116 void GuiDocument::showPreamble()
1117 {
1118         docPS->setCurrentPanel(qt_("LaTeX Preamble"));
1119 }
1120
1121
1122 void GuiDocument::saveDefaultClicked()
1123 {
1124         saveDocDefault();
1125 }
1126
1127
1128 void GuiDocument::useDefaultsClicked()
1129 {
1130         useClassDefaults();
1131 }
1132
1133
1134 void GuiDocument::change_adaptor()
1135 {
1136         changed();
1137 }
1138
1139
1140 void GuiDocument::includeonlyClicked(QTreeWidgetItem * item, int)
1141 {
1142         if (item == 0)
1143                 return;
1144
1145         string child = fromqstr(item->text(0));
1146         if (child.empty())
1147                 return;
1148
1149         if (std::find(includeonlys_.begin(),
1150                       includeonlys_.end(), child) != includeonlys_.end())
1151                 includeonlys_.remove(child);
1152         else
1153                 includeonlys_.push_back(child);
1154         
1155         updateIncludeonlys();
1156         changed();
1157 }
1158
1159
1160 QString GuiDocument::validateListingsParameters()
1161 {
1162         // use a cache here to avoid repeated validation
1163         // of the same parameters
1164         static string param_cache;
1165         static QString msg_cache;
1166         
1167         if (listingsModule->bypassCB->isChecked())
1168                 return QString();
1169
1170         string params = fromqstr(listingsModule->listingsED->toPlainText());
1171         if (params != param_cache) {
1172                 param_cache = params;
1173                 msg_cache = toqstr(InsetListingsParams(params).validate());
1174         }
1175         return msg_cache;
1176 }
1177
1178
1179 void GuiDocument::setListingsMessage()
1180 {
1181         static bool isOK = true;
1182         QString msg = validateListingsParameters();
1183         if (msg.isEmpty()) {
1184                 if (isOK)
1185                         return;
1186                 isOK = true;
1187                 // listingsTB->setTextColor("black");
1188                 listingsModule->listingsTB->setPlainText(
1189                         qt_("Input listings parameters below. "
1190                 "Enter ? for a list of parameters."));
1191         } else {
1192                 isOK = false;
1193                 // listingsTB->setTextColor("red");
1194                 listingsModule->listingsTB->setPlainText(msg);
1195         }
1196 }
1197
1198
1199 void GuiDocument::setLSpacing(int item)
1200 {
1201         textLayoutModule->lspacingLE->setEnabled(item == 3);
1202 }
1203
1204
1205 void GuiDocument::setIndent(int item)
1206 {
1207         bool const enable = (item == 1);
1208         textLayoutModule->indentLE->setEnabled(enable);
1209         textLayoutModule->indentLengthCO->setEnabled(enable);
1210         textLayoutModule->skipLE->setEnabled(false);
1211         textLayoutModule->skipLengthCO->setEnabled(false);
1212         isValid();
1213 }
1214
1215
1216 void GuiDocument::enableIndent(bool indent)
1217 {
1218         textLayoutModule->skipLE->setEnabled(!indent);
1219         textLayoutModule->skipLengthCO->setEnabled(!indent);
1220         if (indent)
1221                 setIndent(textLayoutModule->indentCO->currentIndex());
1222 }
1223
1224
1225 void GuiDocument::setSkip(int item)
1226 {
1227         bool const enable = (item == 3);
1228         textLayoutModule->skipLE->setEnabled(enable);
1229         textLayoutModule->skipLengthCO->setEnabled(enable);
1230         isValid();
1231 }
1232
1233
1234 void GuiDocument::enableSkip(bool skip)
1235 {
1236         textLayoutModule->indentLE->setEnabled(!skip);
1237         textLayoutModule->indentLengthCO->setEnabled(!skip);
1238         if (skip)
1239                 setSkip(textLayoutModule->skipCO->currentIndex());
1240 }
1241
1242
1243 void GuiDocument::portraitChanged()
1244 {
1245         setMargins(pageLayoutModule->papersizeCO->currentIndex());
1246 }
1247
1248
1249 void GuiDocument::setMargins(bool custom)
1250 {
1251         bool const extern_geometry =
1252                 documentClass().provides("geometry");
1253         marginsModule->marginCB->setEnabled(!extern_geometry);
1254         if (extern_geometry) {
1255                 marginsModule->marginCB->setChecked(false);
1256                 setCustomMargins(true);
1257                 return;
1258         }
1259         marginsModule->marginCB->setChecked(custom);
1260         setCustomMargins(custom);
1261 }
1262
1263
1264 void GuiDocument::papersizeChanged(int paper_size)
1265 {
1266         setCustomPapersize(paper_size == 1);
1267 }
1268
1269
1270 void GuiDocument::setCustomPapersize(bool custom)
1271 {
1272         pageLayoutModule->paperwidthL->setEnabled(custom);
1273         pageLayoutModule->paperwidthLE->setEnabled(custom);
1274         pageLayoutModule->paperwidthUnitCO->setEnabled(custom);
1275         pageLayoutModule->paperheightL->setEnabled(custom);
1276         pageLayoutModule->paperheightLE->setEnabled(custom);
1277         pageLayoutModule->paperheightLE->setFocus();
1278         pageLayoutModule->paperheightUnitCO->setEnabled(custom);
1279 }
1280
1281
1282 void GuiDocument::setColSep()
1283 {
1284         setCustomMargins(marginsModule->marginCB->checkState() == Qt::Checked);
1285 }
1286
1287
1288 void GuiDocument::setCustomMargins(bool custom)
1289 {
1290         marginsModule->topL->setEnabled(!custom);
1291         marginsModule->topLE->setEnabled(!custom);
1292         marginsModule->topUnit->setEnabled(!custom);
1293
1294         marginsModule->bottomL->setEnabled(!custom);
1295         marginsModule->bottomLE->setEnabled(!custom);
1296         marginsModule->bottomUnit->setEnabled(!custom);
1297
1298         marginsModule->innerL->setEnabled(!custom);
1299         marginsModule->innerLE->setEnabled(!custom);
1300         marginsModule->innerUnit->setEnabled(!custom);
1301
1302         marginsModule->outerL->setEnabled(!custom);
1303         marginsModule->outerLE->setEnabled(!custom);
1304         marginsModule->outerUnit->setEnabled(!custom);
1305
1306         marginsModule->headheightL->setEnabled(!custom);
1307         marginsModule->headheightLE->setEnabled(!custom);
1308         marginsModule->headheightUnit->setEnabled(!custom);
1309
1310         marginsModule->headsepL->setEnabled(!custom);
1311         marginsModule->headsepLE->setEnabled(!custom);
1312         marginsModule->headsepUnit->setEnabled(!custom);
1313
1314         marginsModule->footskipL->setEnabled(!custom);
1315         marginsModule->footskipLE->setEnabled(!custom);
1316         marginsModule->footskipUnit->setEnabled(!custom);
1317
1318         bool const enableColSep = !custom && 
1319                         textLayoutModule->twoColumnCB->checkState() == Qt::Checked;
1320         marginsModule->columnsepL->setEnabled(enableColSep);
1321         marginsModule->columnsepLE->setEnabled(enableColSep);
1322         marginsModule->columnsepUnit->setEnabled(enableColSep);
1323 }
1324
1325 void GuiDocument::changeBackgroundColor()
1326 {
1327         QColor const & newColor = QColorDialog::getColor(
1328                 rgb2qcolor(set_backgroundcolor), asQWidget());
1329         if (!newColor.isValid())
1330                 return;
1331         // set the button color
1332         pageLayoutModule->backgroundPB->setStyleSheet(
1333                 colorButtonStyleSheet(newColor));
1334         // save color
1335         set_backgroundcolor = rgbFromHexName(fromqstr(newColor.name()));
1336         changed();
1337 }
1338
1339
1340 void GuiDocument::deleteBackgroundColor()
1341 {
1342         // set the button color back to white
1343         pageLayoutModule->backgroundPB->setStyleSheet(
1344                 colorButtonStyleSheet(QColor(Qt::white)));
1345         // save white as the set color
1346         set_backgroundcolor = rgbFromHexName("#ffffff");
1347         changed();
1348 }
1349
1350
1351 void GuiDocument::xetexChanged(bool xetex)
1352 {
1353         updateFontlist();
1354         updateDefaultFormat();
1355         langModule->encodingCO->setEnabled(!xetex &&
1356                 !langModule->defaultencodingRB->isChecked());
1357         langModule->defaultencodingRB->setEnabled(!xetex);
1358         langModule->otherencodingRB->setEnabled(!xetex);
1359
1360         fontModule->fontsDefaultCO->setEnabled(!xetex);
1361         fontModule->fontsDefaultLA->setEnabled(!xetex);
1362         fontModule->cjkFontLE->setEnabled(!xetex);
1363         fontModule->cjkFontLA->setEnabled(!xetex);
1364         string font;
1365         if (!xetex)
1366                 font = tex_fonts_sans[fontModule->fontsSansCO->currentIndex()];
1367         bool scaleable = providesScale(font);
1368         fontModule->scaleSansSB->setEnabled(scaleable);
1369         fontModule->scaleSansLA->setEnabled(scaleable);
1370         if (!xetex)
1371                 font = tex_fonts_monospaced[fontModule->fontsTypewriterCO->currentIndex()];
1372         scaleable = providesScale(font);
1373         fontModule->scaleTypewriterSB->setEnabled(scaleable);
1374         fontModule->scaleTypewriterLA->setEnabled(scaleable);
1375         if (!xetex)
1376                 font = tex_fonts_roman[fontModule->fontsRomanCO->currentIndex()];
1377         fontModule->fontScCB->setEnabled(providesSC(font));
1378         fontModule->fontOsfCB->setEnabled(providesOSF(font));
1379         
1380         fontModule->fontencLA->setEnabled(!xetex);
1381         fontModule->fontencCO->setEnabled(!xetex);
1382         fontModule->fontencLE->setEnabled(!xetex);
1383 }
1384
1385
1386 void GuiDocument::updateFontsize(string const & items, string const & sel)
1387 {
1388         fontModule->fontsizeCO->clear();
1389         fontModule->fontsizeCO->addItem(qt_("Default"));
1390
1391         for (int n = 0; !token(items,'|',n).empty(); ++n)
1392                 fontModule->fontsizeCO->
1393                         addItem(toqstr(token(items,'|',n)));
1394
1395         for (int n = 0; n < fontModule->fontsizeCO->count(); ++n) {
1396                 if (fromqstr(fontModule->fontsizeCO->itemText(n)) == sel) {
1397                         fontModule->fontsizeCO->setCurrentIndex(n);
1398                         break;
1399                 }
1400         }
1401 }
1402
1403
1404 void GuiDocument::updateFontlist()
1405 {
1406         fontModule->fontsRomanCO->clear();
1407         fontModule->fontsSansCO->clear();
1408         fontModule->fontsTypewriterCO->clear();
1409
1410         // With XeTeX, we have access to all system fonts, but not the LaTeX fonts
1411         if (outputModule->xetexCB->isChecked()) {
1412                 fontModule->fontsRomanCO->addItem(qt_("Default"));
1413                 fontModule->fontsSansCO->addItem(qt_("Default"));
1414                 fontModule->fontsTypewriterCO->addItem(qt_("Default"));
1415         
1416                 QFontDatabase fontdb;
1417                 QStringList families(fontdb.families());
1418                 for (QStringList::Iterator it = families.begin(); it != families.end(); ++it) {
1419                         fontModule->fontsRomanCO->addItem(*it);
1420                         fontModule->fontsSansCO->addItem(*it);
1421                         fontModule->fontsTypewriterCO->addItem(*it);
1422                 }
1423                 return;
1424         }
1425
1426         for (int n = 0; tex_fonts_roman[n][0]; ++n) {
1427                 QString font = qt_(tex_fonts_roman_gui[n]);
1428                 if (!isFontAvailable(tex_fonts_roman[n]))
1429                         font += qt_(" (not installed)");
1430                 fontModule->fontsRomanCO->addItem(font);
1431         }
1432         for (int n = 0; tex_fonts_sans[n][0]; ++n) {
1433                 QString font = qt_(tex_fonts_sans_gui[n]);
1434                 if (!isFontAvailable(tex_fonts_sans[n]))
1435                         font += qt_(" (not installed)");
1436                 fontModule->fontsSansCO->addItem(font);
1437         }
1438         for (int n = 0; tex_fonts_monospaced[n][0]; ++n) {
1439                 QString font = qt_(tex_fonts_monospaced_gui[n]);
1440                 if (!isFontAvailable(tex_fonts_monospaced[n]))
1441                         font += qt_(" (not installed)");
1442                 fontModule->fontsTypewriterCO->addItem(font);
1443         }
1444 }
1445
1446
1447 void GuiDocument::fontencChanged(int item)
1448 {
1449         fontModule->fontencLE->setEnabled(item == 1);
1450 }
1451
1452
1453 void GuiDocument::romanChanged(int item)
1454 {
1455         if (outputModule->xetexCB->isChecked())
1456                 return;
1457         string const font = tex_fonts_roman[item];
1458         fontModule->fontScCB->setEnabled(providesSC(font));
1459         fontModule->fontOsfCB->setEnabled(providesOSF(font));
1460 }
1461
1462
1463 void GuiDocument::sansChanged(int item)
1464 {
1465         if (outputModule->xetexCB->isChecked())
1466                 return;
1467         string const font = tex_fonts_sans[item];
1468         bool scaleable = providesScale(font);
1469         fontModule->scaleSansSB->setEnabled(scaleable);
1470         fontModule->scaleSansLA->setEnabled(scaleable);
1471 }
1472
1473
1474 void GuiDocument::ttChanged(int item)
1475 {
1476         if (outputModule->xetexCB->isChecked())
1477                 return;
1478         string const font = tex_fonts_monospaced[item];
1479         bool scaleable = providesScale(font);
1480         fontModule->scaleTypewriterSB->setEnabled(scaleable);
1481         fontModule->scaleTypewriterLA->setEnabled(scaleable);
1482 }
1483
1484
1485 void GuiDocument::updatePagestyle(string const & items, string const & sel)
1486 {
1487         pagestyles.clear();
1488         pageLayoutModule->pagestyleCO->clear();
1489         pageLayoutModule->pagestyleCO->addItem(qt_("Default"));
1490
1491         for (int n = 0; !token(items, '|', n).empty(); ++n) {
1492                 string style = token(items, '|', n);
1493                 QString style_gui = qt_(style);
1494                 pagestyles.push_back(pair<string, QString>(style, style_gui));
1495                 pageLayoutModule->pagestyleCO->addItem(style_gui);
1496         }
1497
1498         if (sel == "default") {
1499                 pageLayoutModule->pagestyleCO->setCurrentIndex(0);
1500                 return;
1501         }
1502
1503         int nn = 0;
1504
1505         for (size_t i = 0; i < pagestyles.size(); ++i)
1506                 if (pagestyles[i].first == sel)
1507                         nn = pageLayoutModule->pagestyleCO->findText(pagestyles[i].second);
1508
1509         if (nn > 0)
1510                 pageLayoutModule->pagestyleCO->setCurrentIndex(nn);
1511 }
1512
1513
1514 void GuiDocument::browseLayout()
1515 {
1516         QString const label1 = qt_("Layouts|#o#O");
1517         QString const dir1 = toqstr(lyxrc.document_path);
1518         QStringList const filter(qt_("LyX Layout (*.layout)"));
1519         QString file = browseRelFile(QString(), bufferFilepath(),
1520                 qt_("Local layout file"), filter, false,
1521                 label1, dir1);
1522
1523         if (!file.endsWith(".layout"))
1524                 return;
1525
1526         FileName layoutFile = support::makeAbsPath(fromqstr(file),
1527                 fromqstr(bufferFilepath()));
1528         
1529         int const ret = Alert::prompt(_("Local layout file"),
1530                 _("The layout file you have selected is a local layout\n"
1531                   "file, not one in the system or user directory. Your\n"
1532                   "document may not work with this layout if you do not\n"
1533                   "keep the layout file in the document directory."),
1534                   1, 1, _("&Set Layout"), _("&Cancel"));
1535         if (ret == 1)
1536                 return;
1537
1538         // load the layout file
1539         LayoutFileList & bcl = LayoutFileList::get();
1540         string classname = layoutFile.onlyFileName();
1541         // this will update an existing layout if that layout has been loaded before.
1542         LayoutFileIndex name = bcl.addLocalLayout(
1543                 classname.substr(0, classname.size() - 7),
1544                 layoutFile.onlyPath().absFilename());
1545
1546         if (name.empty()) {
1547                 Alert::error(_("Error"),
1548                         _("Unable to read local layout file."));                
1549                 return;
1550         }
1551
1552         // do not trigger classChanged if there is no change.
1553         if (latexModule->classCO->currentText() == toqstr(name))
1554                 return;
1555                 
1556         // add to combo box
1557         int idx = latexModule->classCO->findText(toqstr(name));
1558         if (idx == -1) {
1559                 classes_model_.insertRow(0, toqstr(name), name);
1560                 latexModule->classCO->setCurrentIndex(0);
1561         } else
1562                 latexModule->classCO->setCurrentIndex(idx);
1563         
1564         classChanged();
1565 }
1566
1567
1568 void GuiDocument::browseMaster()
1569 {
1570         QString const title = qt_("Select master document");
1571         QString const dir1 = toqstr(lyxrc.document_path);
1572         QString const old = latexModule->childDocLE->text();
1573         QString const docpath = toqstr(support::onlyPath(buffer().absFileName()));
1574         QStringList const filter(qt_("LyX Files (*.lyx)"));
1575         QString file = browseRelFile(old, docpath, title, filter, false,
1576                 qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1577
1578         if (!file.isEmpty())
1579                 latexModule->childDocLE->setText(file);
1580 }
1581
1582
1583 void GuiDocument::classChanged()
1584 {
1585         int idx = latexModule->classCO->currentIndex();
1586         if (idx < 0) 
1587                 return;
1588         string const classname = classes_model_.getIDString(idx);
1589
1590         // check whether the selected modules have changed.
1591         bool modules_changed = false;
1592         unsigned int const srows = selectedModel()->rowCount();
1593         if (srows != bp_.getModules().size())
1594                 modules_changed = true;
1595         else {
1596                 list<string>::const_iterator mit = bp_.getModules().begin();
1597                 list<string>::const_iterator men = bp_.getModules().end();
1598                 for (unsigned int i = 0; i < srows && mit != men; ++i, ++mit)
1599                         if (selectedModel()->getIDString(i) != *mit) {
1600                                 modules_changed = true;
1601                                 break;
1602                         }
1603         }
1604
1605         if (modules_changed || lyxrc.auto_reset_options) {
1606                 if (applyPB->isEnabled()) {
1607                         int const ret = Alert::prompt(_("Unapplied changes"),
1608                                         _("Some changes in the dialog were not yet applied.\n"
1609                                         "If you do not apply now, they will be lost after this action."),
1610                                         1, 1, _("&Apply"), _("&Dismiss"));
1611                         if (ret == 0)
1612                                 applyView();
1613                 }
1614         }
1615
1616         // We load the TextClass as soon as it is selected. This is
1617         // necessary so that other options in the dialog can be updated
1618         // according to the new class. Note, however, that, if you use 
1619         // the scroll wheel when sitting on the combo box, we'll load a 
1620         // lot of TextClass objects very quickly....
1621         if (!bp_.setBaseClass(classname)) {
1622                 Alert::error(_("Error"), _("Unable to set document class."));
1623                 return;
1624         }
1625         if (lyxrc.auto_reset_options)
1626                 bp_.useClassDefaults();
1627
1628         // With the introduction of modules came a distinction between the base 
1629         // class and the document class. The former corresponds to the main layout 
1630         // file; the latter is that plus the modules (or the document-specific layout,
1631         // or  whatever else there could be). Our parameters come from the document 
1632         // class. So when we set the base class, we also need to recreate the document 
1633         // class. Otherwise, we still have the old one.
1634         bp_.makeDocumentClass();
1635         paramsToDialog();
1636 }
1637
1638
1639 void GuiDocument::bibtexChanged(int n)
1640 {
1641         biblioModule->bibtexOptionsED->setEnabled(n != 0);
1642         changed();
1643 }
1644
1645
1646 namespace {
1647         // This is an insanely complicated attempt to make this sort of thing
1648         // work with RTL languages.
1649         docstring formatStrVec(vector<string> const & v, docstring const & s) 
1650         {
1651                 //this mess formats the list as "v[0], v[1], ..., [s] v[n]"
1652                 if (v.size() == 0)
1653                         return docstring();
1654                 if (v.size() == 1) 
1655                         return from_utf8(v[0]);
1656                 if (v.size() == 2) {
1657                         docstring retval = _("%1$s and %2$s");
1658                         retval = subst(retval, _("and"), s);
1659                         return bformat(retval, from_utf8(v[0]), from_utf8(v[1]));
1660                 }
1661                 // The idea here is to format all but the last two items...
1662                 int const vSize = v.size();
1663                 docstring t2 = _("%1$s, %2$s");
1664                 docstring retval = from_utf8(v[0]);
1665                 for (int i = 1; i < vSize - 2; ++i)
1666                         retval = bformat(t2, retval, from_utf8(v[i])); 
1667                 //...and then to  plug them, and the last two, into this schema
1668                 docstring t = _("%1$s, %2$s, and %3$s");
1669                 t = subst(t, _("and"), s);
1670                 return bformat(t, retval, from_utf8(v[vSize - 2]), from_utf8(v[vSize - 1]));
1671         }
1672         
1673         vector<string> idsToNames(vector<string> const & idList)
1674         {
1675                 vector<string> retval;
1676                 vector<string>::const_iterator it  = idList.begin();
1677                 vector<string>::const_iterator end = idList.end();
1678                 for (; it != end; ++it) {
1679                         LyXModule const * const mod = theModuleList[*it];
1680                         if (!mod)
1681                                 retval.push_back(*it + " (Unavailable)");
1682                         else
1683                                 retval.push_back(mod->getName());
1684                 }
1685                 return retval;
1686         }
1687 }
1688
1689
1690 void GuiDocument::modulesToParams(BufferParams & bp)
1691 {
1692         // update list of loaded modules
1693         bp.clearLayoutModules();
1694         int const srows = modules_sel_model_.rowCount();
1695         for (int i = 0; i < srows; ++i)
1696                 bp.addLayoutModule(modules_sel_model_.getIDString(i));
1697
1698         // update the list of removed modules
1699         bp.clearRemovedModules();
1700         LayoutModuleList const & reqmods = bp.baseClass()->defaultModules();
1701         list<string>::const_iterator rit = reqmods.begin();
1702         list<string>::const_iterator ren = reqmods.end();
1703
1704         // check each of the default modules
1705         for (; rit != ren; rit++) {
1706                 list<string>::const_iterator mit = bp.getModules().begin();
1707                 list<string>::const_iterator men = bp.getModules().end();
1708                 bool found = false;
1709                 for (; mit != men; mit++) {
1710                         if (*rit == *mit) {
1711                                 found = true;
1712                                 break;
1713                         }
1714                 }
1715                 if (!found) {
1716                         // the module isn't present so must have been removed by the user
1717                         bp.addRemovedModule(*rit);
1718                 }
1719         }
1720 }
1721
1722 void GuiDocument::modulesChanged()
1723 {
1724         modulesToParams(bp_);
1725         bp_.makeDocumentClass();
1726         paramsToDialog();
1727 }
1728
1729
1730 void GuiDocument::updateModuleInfo()
1731 {
1732         selectionManager->update();
1733         
1734         //Module description
1735         bool const focus_on_selected = selectionManager->selectedFocused();
1736         QAbstractItemView * lv;
1737         if (focus_on_selected)
1738                 lv = modulesModule->selectedLV;
1739         else
1740                 lv= modulesModule->availableLV;
1741         if (lv->selectionModel()->selectedIndexes().isEmpty()) {
1742                 modulesModule->infoML->document()->clear();
1743                 return;
1744         }
1745         QModelIndex const & idx = lv->selectionModel()->currentIndex();
1746         GuiIdListModel const & id_model = 
1747                         focus_on_selected  ? modules_sel_model_ : modules_av_model_;
1748         string const modName = id_model.getIDString(idx.row());
1749         docstring desc = getModuleDescription(modName);
1750
1751         LayoutModuleList const & provmods = bp_.baseClass()->providedModules();
1752         if (std::find(provmods.begin(), provmods.end(), modName) != provmods.end()) {
1753                 if (!desc.empty())
1754                         desc += "\n";
1755                 desc += _("Module provided by document class.");
1756         }
1757
1758         vector<string> pkglist = getPackageList(modName);
1759         docstring pkgdesc = formatStrVec(pkglist, _("and"));
1760         if (!pkgdesc.empty()) {
1761                 if (!desc.empty())
1762                         desc += "\n";
1763                 desc += bformat(_("Package(s) required: %1$s."), pkgdesc);
1764         }
1765
1766         pkglist = getRequiredList(modName);
1767         if (!pkglist.empty()) {
1768                 vector<string> const reqdescs = idsToNames(pkglist);
1769                 pkgdesc = formatStrVec(reqdescs, _("or"));
1770                 if (!desc.empty())
1771                         desc += "\n";
1772                 desc += bformat(_("Module required: %1$s."), pkgdesc);
1773         }
1774
1775         pkglist = getExcludedList(modName);
1776         if (!pkglist.empty()) {
1777                 vector<string> const reqdescs = idsToNames(pkglist);
1778                 pkgdesc = formatStrVec(reqdescs, _( "and"));
1779                 if (!desc.empty())
1780                         desc += "\n";
1781                 desc += bformat(_("Modules excluded: %1$s."), pkgdesc);
1782         }
1783
1784         if (!isModuleAvailable(modName)) {
1785                 if (!desc.empty())
1786                         desc += "\n";
1787                 desc += _("WARNING: Some required packages are unavailable!");
1788         }
1789
1790         modulesModule->infoML->document()->setPlainText(toqstr(desc));
1791 }
1792
1793
1794 void GuiDocument::updateNumbering()
1795 {
1796         DocumentClass const & tclass = documentClass();
1797
1798         numberingModule->tocTW->setUpdatesEnabled(false);
1799         numberingModule->tocTW->clear();
1800
1801         int const depth = numberingModule->depthSL->value();
1802         int const toc = numberingModule->tocSL->value();
1803         QString const no = qt_("No");
1804         QString const yes = qt_("Yes");
1805         QTreeWidgetItem * item = 0;
1806
1807         DocumentClass::const_iterator lit = tclass.begin();
1808         DocumentClass::const_iterator len = tclass.end();
1809         for (; lit != len; ++lit) {
1810                 int const toclevel = lit->toclevel;
1811                 if (toclevel != Layout::NOT_IN_TOC && lit->labeltype == LABEL_COUNTER) {
1812                         item = new QTreeWidgetItem(numberingModule->tocTW);
1813                         item->setText(0, toqstr(translateIfPossible(lit->name())));
1814                         item->setText(1, (toclevel <= depth) ? yes : no);
1815                         item->setText(2, (toclevel <= toc) ? yes : no);
1816                 }
1817         }
1818
1819         numberingModule->tocTW->setUpdatesEnabled(true);
1820         numberingModule->tocTW->update();
1821 }
1822
1823
1824 void GuiDocument::updateDefaultFormat()
1825 {
1826         if (!bufferview())
1827                 return;
1828         // make a copy in order to consider unapplied changes
1829         Buffer * tmpbuf = const_cast<Buffer *>(&buffer());
1830         tmpbuf->params().useXetex = outputModule->xetexCB->isChecked();
1831         int idx = latexModule->classCO->currentIndex();
1832         if (idx >= 0) {
1833                 string const classname = classes_model_.getIDString(idx);
1834                 tmpbuf->params().setBaseClass(classname);
1835                 tmpbuf->params().makeDocumentClass();
1836         }
1837         outputModule->defaultFormatCO->blockSignals(true);
1838         outputModule->defaultFormatCO->clear();
1839         outputModule->defaultFormatCO->addItem(qt_("Default"),
1840                                 QVariant(QString("default")));
1841         typedef vector<Format const *> Formats;
1842         Formats formats = tmpbuf->exportableFormats(true);
1843         Formats::const_iterator cit = formats.begin();
1844         Formats::const_iterator end = formats.end();
1845         for (; cit != end; ++cit)
1846                 outputModule->defaultFormatCO->addItem(qt_((*cit)->prettyname()),
1847                                 QVariant(toqstr((*cit)->name())));
1848         outputModule->defaultFormatCO->blockSignals(false);
1849 }
1850
1851
1852 bool GuiDocument::isChildIncluded(string const & child)
1853 {
1854         if (includeonlys_.empty())
1855                 return false;
1856         return (std::find(includeonlys_.begin(),
1857                           includeonlys_.end(), child) != includeonlys_.end());
1858 }
1859
1860
1861 void GuiDocument::applyView()
1862 {
1863         // preamble
1864         preambleModule->apply(bp_);
1865
1866         // date
1867         bp_.suppress_date = latexModule->suppressDateCB->isChecked();
1868
1869         // biblio
1870         bp_.setCiteEngine(ENGINE_BASIC);
1871
1872         if (biblioModule->citeNatbibRB->isChecked()) {
1873                 bool const use_numerical_citations =
1874                         biblioModule->citeStyleCO->currentIndex();
1875                 if (use_numerical_citations)
1876                         bp_.setCiteEngine(ENGINE_NATBIB_NUMERICAL);
1877                 else
1878                         bp_.setCiteEngine(ENGINE_NATBIB_AUTHORYEAR);
1879
1880         } else if (biblioModule->citeJurabibRB->isChecked())
1881                 bp_.setCiteEngine(ENGINE_JURABIB);
1882
1883         bp_.use_bibtopic =
1884                 biblioModule->bibtopicCB->isChecked();
1885
1886         string const bibtex_command =
1887                 fromqstr(biblioModule->bibtexCO->itemData(
1888                         biblioModule->bibtexCO->currentIndex()).toString());
1889         string const bibtex_options =
1890                 fromqstr(biblioModule->bibtexOptionsED->text());
1891         if (bibtex_command == "default" || bibtex_options.empty())
1892                 bp_.bibtex_command = bibtex_command;
1893         else
1894                 bp_.bibtex_command = bibtex_command + " " + bibtex_options;
1895
1896         // Indices
1897         indicesModule->apply(bp_);
1898
1899         // language & quotes
1900         if (langModule->defaultencodingRB->isChecked()) {
1901                 bp_.inputenc = "auto";
1902         } else {
1903                 int i = langModule->encodingCO->currentIndex();
1904                 if (i == 0)
1905                         bp_.inputenc = "default";
1906                 else {
1907                         QString const enc_gui =
1908                                 langModule->encodingCO->currentText();
1909                         Encodings::const_iterator it = encodings.begin();
1910                         Encodings::const_iterator const end = encodings.end();
1911                         bool found = false;
1912                         for (; it != end; ++it) {
1913                                 if (qt_(it->guiName()) == enc_gui) {
1914                                         bp_.inputenc = it->latexName();
1915                                         found = true;
1916                                         break;
1917                                 }
1918                         }
1919                         if (!found) {
1920                                 // should not happen
1921                                 lyxerr << "GuiDocument::apply: Unknown encoding! Resetting to default" << endl;
1922                                 bp_.inputenc = "default";
1923                         }
1924                 }
1925         }
1926
1927         InsetQuotes::QuoteLanguage lga = InsetQuotes::EnglishQuotes;
1928         switch (langModule->quoteStyleCO->currentIndex()) {
1929         case 0:
1930                 lga = InsetQuotes::EnglishQuotes;
1931                 break;
1932         case 1:
1933                 lga = InsetQuotes::SwedishQuotes;
1934                 break;
1935         case 2:
1936                 lga = InsetQuotes::GermanQuotes;
1937                 break;
1938         case 3:
1939                 lga = InsetQuotes::PolishQuotes;
1940                 break;
1941         case 4:
1942                 lga = InsetQuotes::FrenchQuotes;
1943                 break;
1944         case 5:
1945                 lga = InsetQuotes::DanishQuotes;
1946                 break;
1947         }
1948         bp_.quotes_language = lga;
1949
1950         QString const lang = langModule->languageCO->itemData(
1951                 langModule->languageCO->currentIndex()).toString();
1952         bp_.language = lyx::languages.getLanguage(fromqstr(lang));
1953
1954         // numbering
1955         if (bp_.documentClass().hasTocLevels()) {
1956                 bp_.tocdepth = numberingModule->tocSL->value();
1957                 bp_.secnumdepth = numberingModule->depthSL->value();
1958         }
1959
1960         // bullets
1961         bp_.user_defined_bullet(0) = bulletsModule->bullet(0);
1962         bp_.user_defined_bullet(1) = bulletsModule->bullet(1);
1963         bp_.user_defined_bullet(2) = bulletsModule->bullet(2);
1964         bp_.user_defined_bullet(3) = bulletsModule->bullet(3);
1965
1966         // packages
1967         bp_.graphicsDriver =
1968                 tex_graphics[latexModule->psdriverCO->currentIndex()];
1969         
1970         // text layout
1971         int idx = latexModule->classCO->currentIndex();
1972         if (idx >= 0) {
1973                 string const classname = classes_model_.getIDString(idx);
1974                 bp_.setBaseClass(classname);
1975         }
1976
1977         // Modules
1978         modulesToParams(bp_);
1979
1980         // Math
1981         if (mathsModule->amsautoCB->isChecked()) {
1982                 bp_.use_amsmath = BufferParams::package_auto;
1983         } else {
1984                 if (mathsModule->amsCB->isChecked())
1985                         bp_.use_amsmath = BufferParams::package_on;
1986                 else
1987                         bp_.use_amsmath = BufferParams::package_off;
1988         }
1989         if (mathsModule->esintautoCB->isChecked())
1990                 bp_.use_esint = BufferParams::package_auto;
1991         else {
1992                 if (mathsModule->esintCB->isChecked())
1993                         bp_.use_esint = BufferParams::package_on;
1994                 else
1995                         bp_.use_esint = BufferParams::package_off;
1996         }
1997         if (mathsModule->mhchemautoCB->isChecked())
1998                 bp_.use_mhchem = BufferParams::package_auto;
1999         else {
2000                 if (mathsModule->mhchemCB->isChecked())
2001                         bp_.use_mhchem = BufferParams::package_on;
2002                 else
2003                         bp_.use_mhchem = BufferParams::package_off;
2004         }
2005
2006         // Page Layout
2007         if (pageLayoutModule->pagestyleCO->currentIndex() == 0)
2008                 bp_.pagestyle = "default";
2009         else {
2010                 QString style_gui = pageLayoutModule->pagestyleCO->currentText();
2011                 for (size_t i = 0; i != pagestyles.size(); ++i)
2012                         if (pagestyles[i].second == style_gui)
2013                                 bp_.pagestyle = pagestyles[i].first;
2014         }
2015
2016         // Text Layout
2017         switch (textLayoutModule->lspacingCO->currentIndex()) {
2018         case 0:
2019                 bp_.spacing().set(Spacing::Single);
2020                 break;
2021         case 1:
2022                 bp_.spacing().set(Spacing::Onehalf);
2023                 break;
2024         case 2:
2025                 bp_.spacing().set(Spacing::Double);
2026                 break;
2027         case 3:
2028                 bp_.spacing().set(Spacing::Other,
2029                         widgetToDoubleStr(textLayoutModule->lspacingLE));
2030                 break;
2031         }
2032
2033         if (textLayoutModule->twoColumnCB->isChecked())
2034                 bp_.columns = 2;
2035         else
2036                 bp_.columns = 1;
2037
2038         if (textLayoutModule->indentRB->isChecked()) {
2039                 // if paragraphs are separated by an indentation
2040                 bp_.paragraph_separation = BufferParams::ParagraphIndentSeparation;
2041                 switch (textLayoutModule->indentCO->currentIndex()) {
2042                 case 0:
2043                         bp_.setIndentation(HSpace(HSpace::DEFAULT));
2044                         break;
2045                 case 1: {
2046                         HSpace indent = HSpace(
2047                                 widgetsToLength(textLayoutModule->indentLE,
2048                                 textLayoutModule->indentLengthCO)
2049                                 );
2050                         bp_.setIndentation(indent);
2051                         break;
2052                         }
2053                 default:
2054                         // this should never happen
2055                         bp_.setIndentation(HSpace(HSpace::DEFAULT));
2056                         break;
2057                 }
2058         } else {
2059                 // if paragraphs are separated by a skip
2060                 bp_.paragraph_separation = BufferParams::ParagraphSkipSeparation;
2061                 switch (textLayoutModule->skipCO->currentIndex()) {
2062                 case 0:
2063                         bp_.setDefSkip(VSpace(VSpace::SMALLSKIP));
2064                         break;
2065                 case 1:
2066                         bp_.setDefSkip(VSpace(VSpace::MEDSKIP));
2067                         break;
2068                 case 2:
2069                         bp_.setDefSkip(VSpace(VSpace::BIGSKIP));
2070                         break;
2071                 case 3:
2072                         {
2073                         VSpace vs = VSpace(
2074                                 widgetsToLength(textLayoutModule->skipLE,
2075                                 textLayoutModule->skipLengthCO)
2076                                 );
2077                         bp_.setDefSkip(vs);
2078                         break;
2079                         }
2080                 default:
2081                         // this should never happen
2082                         bp_.setDefSkip(VSpace(VSpace::MEDSKIP));
2083                         break;
2084                 }
2085         }
2086
2087         bp_.options =
2088                 fromqstr(latexModule->optionsLE->text());
2089
2090         bp_.use_default_options =
2091                 latexModule->defaultOptionsCB->isChecked();
2092
2093         if (latexModule->childDocGB->isChecked())
2094                 bp_.master =
2095                         fromqstr(latexModule->childDocLE->text());
2096         else
2097                 bp_.master = string();
2098
2099         // Master/Child
2100         bp_.clearIncludedChildren();
2101         if (masterChildModule->includeonlyRB->isChecked()) {
2102                 list<string>::const_iterator it = includeonlys_.begin();
2103                 for (; it != includeonlys_.end() ; ++it) {
2104                         bp_.addIncludedChildren(*it);
2105                 }
2106         }
2107         bp_.maintain_unincluded_children =
2108                 masterChildModule->maintainAuxCB->isChecked();
2109
2110         // Float Placement
2111         bp_.float_placement = floatModule->get();
2112
2113         // Listings
2114         // text should have passed validation
2115         bp_.listings_params =
2116                 InsetListingsParams(fromqstr(listingsModule->listingsED->toPlainText())).params();
2117
2118         // output
2119         bp_.defaultOutputFormat = fromqstr(outputModule->defaultFormatCO->itemData(
2120                 outputModule->defaultFormatCO->currentIndex()).toString());
2121
2122         bool const xetex = outputModule->xetexCB->isChecked();
2123         bp_.useXetex = xetex;
2124
2125         // fonts
2126         if (xetex) {
2127                 if (fontModule->fontsRomanCO->currentIndex() == 0)
2128                         bp_.fontsRoman = "default";
2129                 else
2130                         bp_.fontsRoman =
2131                                 fromqstr(fontModule->fontsRomanCO->currentText());
2132         
2133                 if (fontModule->fontsSansCO->currentIndex() == 0)
2134                         bp_.fontsSans = "default";
2135                 else
2136                         bp_.fontsSans =
2137                                 fromqstr(fontModule->fontsSansCO->currentText());
2138         
2139                 if (fontModule->fontsTypewriterCO->currentIndex() == 0)
2140                         bp_.fontsTypewriter = "default";
2141                 else
2142                         bp_.fontsTypewriter =
2143                                 fromqstr(fontModule->fontsTypewriterCO->currentText());
2144         } else {
2145                 bp_.fontsRoman =
2146                         tex_fonts_roman[fontModule->fontsRomanCO->currentIndex()];
2147         
2148                 bp_.fontsSans =
2149                         tex_fonts_sans[fontModule->fontsSansCO->currentIndex()];
2150         
2151                 bp_.fontsTypewriter =
2152                         tex_fonts_monospaced[fontModule->fontsTypewriterCO->currentIndex()];
2153         }
2154
2155         if (fontModule->fontencCO->currentIndex() == 0)
2156                 bp_.fontenc = "global";
2157         else if (fontModule->fontencCO->currentIndex() == 1)
2158                 bp_.fontenc = fromqstr(fontModule->fontencLE->text());
2159         else if (fontModule->fontencCO->currentIndex() == 2)
2160                 bp_.fontenc = "default";
2161
2162         bp_.fontsCJK =
2163                 fromqstr(fontModule->cjkFontLE->text());
2164
2165         bp_.fontsSansScale = fontModule->scaleSansSB->value();
2166
2167         bp_.fontsTypewriterScale = fontModule->scaleTypewriterSB->value();
2168
2169         bp_.fontsSC = fontModule->fontScCB->isChecked();
2170
2171         bp_.fontsOSF = fontModule->fontOsfCB->isChecked();
2172
2173         if (xetex)
2174                 bp_.fontsDefaultFamily = "default";
2175         else
2176                 bp_.fontsDefaultFamily = GuiDocument::fontfamilies[
2177                         fontModule->fontsDefaultCO->currentIndex()];
2178
2179         if (fontModule->fontsizeCO->currentIndex() == 0)
2180                 bp_.fontsize = "default";
2181         else
2182                 bp_.fontsize =
2183                         fromqstr(fontModule->fontsizeCO->currentText());
2184
2185         // paper
2186         bp_.papersize = PAPER_SIZE(
2187                 pageLayoutModule->papersizeCO->currentIndex());
2188
2189         // custom, A3, B3 and B4 paper sizes need geometry
2190         int psize = pageLayoutModule->papersizeCO->currentIndex();
2191         bool geom_papersize = (psize == 1 || psize == 5 || psize == 8 || psize == 9);
2192
2193         bp_.paperwidth = widgetsToLength(pageLayoutModule->paperwidthLE,
2194                 pageLayoutModule->paperwidthUnitCO);
2195
2196         bp_.paperheight = widgetsToLength(pageLayoutModule->paperheightLE,
2197                 pageLayoutModule->paperheightUnitCO);
2198
2199         if (pageLayoutModule->facingPagesCB->isChecked())
2200                 bp_.sides = TwoSides;
2201         else
2202                 bp_.sides = OneSide;
2203
2204         if (pageLayoutModule->landscapeRB->isChecked())
2205                 bp_.orientation = ORIENTATION_LANDSCAPE;
2206         else
2207                 bp_.orientation = ORIENTATION_PORTRAIT;
2208
2209         bp_.backgroundcolor = set_backgroundcolor;
2210
2211         // margins
2212         bp_.use_geometry = !marginsModule->marginCB->isChecked()
2213                 || geom_papersize;
2214
2215         Ui::MarginsUi const * m = marginsModule;
2216
2217         bp_.leftmargin = widgetsToLength(m->innerLE, m->innerUnit);
2218         bp_.topmargin = widgetsToLength(m->topLE, m->topUnit);
2219         bp_.rightmargin = widgetsToLength(m->outerLE, m->outerUnit);
2220         bp_.bottommargin = widgetsToLength(m->bottomLE, m->bottomUnit);
2221         bp_.headheight = widgetsToLength(m->headheightLE, m->headheightUnit);
2222         bp_.headsep = widgetsToLength(m->headsepLE, m->headsepUnit);
2223         bp_.footskip = widgetsToLength(m->footskipLE, m->footskipUnit);
2224         bp_.columnsep = widgetsToLength(m->columnsepLE, m->columnsepUnit);
2225
2226         // branches
2227         branchesModule->apply(bp_);
2228
2229         // PDF support
2230         PDFOptions & pdf = bp_.pdfoptions();
2231         pdf.use_hyperref = pdfSupportModule->use_hyperrefGB->isChecked();
2232         pdf.title = fromqstr(pdfSupportModule->titleLE->text());
2233         pdf.author = fromqstr(pdfSupportModule->authorLE->text());
2234         pdf.subject = fromqstr(pdfSupportModule->subjectLE->text());
2235         pdf.keywords = fromqstr(pdfSupportModule->keywordsLE->text());
2236
2237         pdf.bookmarks = pdfSupportModule->bookmarksGB->isChecked();
2238         pdf.bookmarksnumbered = pdfSupportModule->bookmarksnumberedCB->isChecked();
2239         pdf.bookmarksopen = pdfSupportModule->bookmarksopenGB->isChecked();
2240         pdf.bookmarksopenlevel = pdfSupportModule->bookmarksopenlevelSB->value();
2241
2242         pdf.breaklinks = pdfSupportModule->breaklinksCB->isChecked();
2243         pdf.pdfborder = pdfSupportModule->pdfborderCB->isChecked();
2244         pdf.pdfusetitle = pdfSupportModule->pdfusetitleCB->isChecked();
2245         pdf.colorlinks = pdfSupportModule->colorlinksCB->isChecked();
2246         pdf.backref =
2247                 backref_opts[pdfSupportModule->backrefCO->currentIndex()];
2248         if (pdfSupportModule->fullscreenCB->isChecked())
2249                 pdf.pagemode = pdf.pagemode_fullscreen;
2250         else
2251                 pdf.pagemode.clear();
2252         pdf.quoted_options = pdf.quoted_options_check(
2253                                 fromqstr(pdfSupportModule->optionsLE->text()));
2254 }
2255
2256
2257 void GuiDocument::paramsToDialog()
2258 {
2259         // set the default unit
2260         Length::UNIT const defaultUnit = Length::defaultUnit();
2261
2262         // preamble
2263         preambleModule->update(bp_, id());
2264
2265         // date
2266         latexModule->suppressDateCB->setChecked(bp_.suppress_date);
2267
2268         // biblio
2269         biblioModule->citeDefaultRB->setChecked(
2270                 bp_.citeEngine() == ENGINE_BASIC);
2271
2272         biblioModule->citeNatbibRB->setChecked(
2273                 bp_.citeEngine() == ENGINE_NATBIB_NUMERICAL ||
2274                 bp_.citeEngine() == ENGINE_NATBIB_AUTHORYEAR);
2275
2276         biblioModule->citeStyleCO->setCurrentIndex(
2277                 bp_.citeEngine() == ENGINE_NATBIB_NUMERICAL);
2278
2279         biblioModule->citeJurabibRB->setChecked(
2280                 bp_.citeEngine() == ENGINE_JURABIB);
2281
2282         biblioModule->bibtopicCB->setChecked(
2283                 bp_.use_bibtopic);
2284
2285         string command;
2286         string options =
2287                 split(bp_.bibtex_command, command, ' ');
2288
2289         int const bpos = biblioModule->bibtexCO->findData(toqstr(command));
2290         if (bpos != -1) {
2291                 biblioModule->bibtexCO->setCurrentIndex(bpos);
2292                 biblioModule->bibtexOptionsED->setText(toqstr(options).trimmed());
2293         } else {
2294                 biblioModule->bibtexCO->setCurrentIndex(0);
2295                 biblioModule->bibtexOptionsED->clear();
2296         }
2297         biblioModule->bibtexOptionsED->setEnabled(
2298                 biblioModule->bibtexCO->currentIndex() != 0);
2299
2300         // indices
2301         indicesModule->update(bp_);
2302
2303         // language & quotes
2304         int const pos = langModule->languageCO->findData(toqstr(
2305                 bp_.language->lang()));
2306         langModule->languageCO->setCurrentIndex(pos);
2307
2308         langModule->quoteStyleCO->setCurrentIndex(
2309                 bp_.quotes_language);
2310
2311         bool default_enc = true;
2312         if (bp_.inputenc != "auto") {
2313                 default_enc = false;
2314                 if (bp_.inputenc == "default") {
2315                         langModule->encodingCO->setCurrentIndex(0);
2316                 } else {
2317                         string enc_gui;
2318                         Encodings::const_iterator it = encodings.begin();
2319                         Encodings::const_iterator const end = encodings.end();
2320                         for (; it != end; ++it) {
2321                                 if (it->latexName() == bp_.inputenc) {
2322                                         enc_gui = it->guiName();
2323                                         break;
2324                                 }
2325                         }
2326                         int const i = langModule->encodingCO->findText(
2327                                         qt_(enc_gui));
2328                         if (i >= 0)
2329                                 langModule->encodingCO->setCurrentIndex(i);
2330                         else
2331                                 // unknown encoding. Set to default.
2332                                 default_enc = true;
2333                 }
2334         }
2335         langModule->defaultencodingRB->setChecked(default_enc);
2336         langModule->otherencodingRB->setChecked(!default_enc);
2337
2338         // numbering
2339         int const min_toclevel = documentClass().min_toclevel();
2340         int const max_toclevel = documentClass().max_toclevel();
2341         if (documentClass().hasTocLevels()) {
2342                 numberingModule->setEnabled(true);
2343                 numberingModule->depthSL->setMinimum(min_toclevel - 1);
2344                 numberingModule->depthSL->setMaximum(max_toclevel);
2345                 numberingModule->depthSL->setValue(bp_.secnumdepth);
2346                 numberingModule->tocSL->setMaximum(min_toclevel - 1);
2347                 numberingModule->tocSL->setMaximum(max_toclevel);
2348                 numberingModule->tocSL->setValue(bp_.tocdepth);
2349                 updateNumbering();
2350         } else {
2351                 numberingModule->setEnabled(false);
2352                 numberingModule->tocTW->clear();
2353         }
2354
2355         // bullets
2356         bulletsModule->setBullet(0, bp_.user_defined_bullet(0));
2357         bulletsModule->setBullet(1, bp_.user_defined_bullet(1));
2358         bulletsModule->setBullet(2, bp_.user_defined_bullet(2));
2359         bulletsModule->setBullet(3, bp_.user_defined_bullet(3));
2360         bulletsModule->init();
2361
2362         // packages
2363         int nitem = findToken(tex_graphics, bp_.graphicsDriver);
2364         if (nitem >= 0)
2365                 latexModule->psdriverCO->setCurrentIndex(nitem);
2366         updateModuleInfo();
2367         
2368         mathsModule->amsCB->setChecked(
2369                 bp_.use_amsmath == BufferParams::package_on);
2370         mathsModule->amsautoCB->setChecked(
2371                 bp_.use_amsmath == BufferParams::package_auto);
2372
2373         mathsModule->esintCB->setChecked(
2374                 bp_.use_esint == BufferParams::package_on);
2375         mathsModule->esintautoCB->setChecked(
2376                 bp_.use_esint == BufferParams::package_auto);
2377
2378         mathsModule->mhchemCB->setChecked(
2379                 bp_.use_mhchem == BufferParams::package_on);
2380         mathsModule->mhchemautoCB->setChecked(
2381                 bp_.use_mhchem == BufferParams::package_auto);
2382
2383         switch (bp_.spacing().getSpace()) {
2384                 case Spacing::Other: nitem = 3; break;
2385                 case Spacing::Double: nitem = 2; break;
2386                 case Spacing::Onehalf: nitem = 1; break;
2387                 case Spacing::Default: case Spacing::Single: nitem = 0; break;
2388         }
2389
2390         // text layout
2391         string const & layoutID = bp_.baseClassID();
2392         setLayoutComboByIDString(layoutID);
2393
2394         updatePagestyle(documentClass().opt_pagestyle(),
2395                                  bp_.pagestyle);
2396
2397         textLayoutModule->lspacingCO->setCurrentIndex(nitem);
2398         if (bp_.spacing().getSpace() == Spacing::Other) {
2399                 doubleToWidget(textLayoutModule->lspacingLE,
2400                         bp_.spacing().getValueAsString());
2401         }
2402         setLSpacing(nitem);
2403
2404         if (bp_.paragraph_separation == BufferParams::ParagraphIndentSeparation) {
2405                 textLayoutModule->indentRB->setChecked(true);
2406                 string indentation = bp_.getIndentation().asLyXCommand();
2407                 int indent = 0;
2408                 if (indentation != "default") {
2409                         lengthToWidgets(textLayoutModule->indentLE,
2410                         textLayoutModule->indentLengthCO,
2411                         indentation, defaultUnit);
2412                         indent = 1;
2413                 }
2414                 textLayoutModule->indentCO->setCurrentIndex(indent);
2415                 setIndent(indent);
2416         } else {
2417                 textLayoutModule->skipRB->setChecked(true);
2418                 int skip = 0;
2419                 switch (bp_.getDefSkip().kind()) {
2420                 case VSpace::SMALLSKIP:
2421                         skip = 0;
2422                         break;
2423                 case VSpace::MEDSKIP:
2424                         skip = 1;
2425                         break;
2426                 case VSpace::BIGSKIP:
2427                         skip = 2;
2428                         break;
2429                 case VSpace::LENGTH:
2430                         {
2431                         skip = 3;
2432                         string const length = bp_.getDefSkip().asLyXCommand();
2433                         lengthToWidgets(textLayoutModule->skipLE,
2434                                 textLayoutModule->skipLengthCO,
2435                                 length, defaultUnit);
2436                         break;
2437                         }
2438                 default:
2439                         skip = 0;
2440                         break;
2441                 }
2442                 textLayoutModule->skipCO->setCurrentIndex(skip);
2443                 setSkip(skip);
2444         }
2445
2446         textLayoutModule->twoColumnCB->setChecked(
2447                 bp_.columns == 2);
2448
2449         if (!bp_.options.empty()) {
2450                 latexModule->optionsLE->setText(
2451                         toqstr(bp_.options));
2452         } else {
2453                 latexModule->optionsLE->setText(QString());
2454         }
2455
2456         // latex
2457         latexModule->defaultOptionsCB->setChecked(
2458                         bp_.use_default_options);
2459         updateSelectedModules();
2460         selectionManager->updateProvidedModules(
2461                         bp_.baseClass()->providedModules());
2462         selectionManager->updateExcludedModules(
2463                         bp_.baseClass()->excludedModules());
2464
2465         if (!documentClass().options().empty()) {
2466                 latexModule->defaultOptionsLE->setText(
2467                         toqstr(documentClass().options()));
2468         } else {
2469                 latexModule->defaultOptionsLE->setText(
2470                         toqstr(_("[No options predefined]")));
2471         }
2472
2473         latexModule->defaultOptionsLE->setEnabled(
2474                 bp_.use_default_options
2475                 && !documentClass().options().empty());
2476
2477         latexModule->defaultOptionsCB->setEnabled(
2478                 !documentClass().options().empty());
2479
2480         if (!bp_.master.empty()) {
2481                 latexModule->childDocGB->setChecked(true);
2482                 latexModule->childDocLE->setText(
2483                         toqstr(bp_.master));
2484         } else {
2485                 latexModule->childDocLE->setText(QString());
2486                 latexModule->childDocGB->setChecked(false);
2487         }
2488
2489         // Master/Child
2490         std::vector<Buffer *> children;
2491         if (bufferview())
2492                 children = buffer().getChildren(false);
2493         if (children.empty()) {
2494                 masterChildModule->childrenTW->clear();
2495                 includeonlys_.clear();
2496                 docPS->showPanel(qt_("Child Documents"), false);
2497                 if (docPS->isCurrentPanel(qt_("Child Documents")))
2498                         docPS->setCurrentPanel(qt_("Document Class"));
2499         } else {
2500                 docPS->showPanel(qt_("Child Documents"), true);
2501                 masterChildModule->setEnabled(true);
2502                 includeonlys_ = bp_.getIncludedChildren();
2503                 updateIncludeonlys();
2504         }
2505         masterChildModule->maintainAuxCB->setChecked(
2506                 bp_.maintain_unincluded_children);
2507
2508         // Float Settings
2509         floatModule->set(bp_.float_placement);
2510
2511         // ListingsSettings
2512         // break listings_params to multiple lines
2513         string lstparams =
2514                 InsetListingsParams(bp_.listings_params).separatedParams();
2515         listingsModule->listingsED->setPlainText(toqstr(lstparams));
2516
2517         // Output
2518         // update combobox with formats
2519         updateDefaultFormat();
2520         int index = outputModule->defaultFormatCO->findData(toqstr(
2521                 bp_.defaultOutputFormat));
2522         // set to default if format is not found 
2523         if (index == -1)
2524                 index = 0;
2525         outputModule->defaultFormatCO->setCurrentIndex(index);
2526         outputModule->xetexCB->setEnabled(bp_.baseClass()->outputType() == lyx::LATEX);
2527         outputModule->xetexCB->setChecked(
2528                 bp_.baseClass()->outputType() == lyx::LATEX && bp_.useXetex);
2529
2530         // Fonts
2531         updateFontsize(documentClass().opt_fontsize(),
2532                         bp_.fontsize);
2533
2534         if (bp_.useXetex) {
2535                 fontModule->fontencLA->setEnabled(false);
2536                 fontModule->fontencCO->setEnabled(false);
2537                 fontModule->fontencLE->setEnabled(false);
2538                 for (int i = 0; i < fontModule->fontsRomanCO->count(); ++i) {
2539                         if (fontModule->fontsRomanCO->itemText(i) == toqstr(bp_.fontsRoman)) {
2540                                 fontModule->fontsRomanCO->setCurrentIndex(i);
2541                                 return;
2542                         }
2543                 }
2544                 
2545                 for (int i = 0; i < fontModule->fontsSansCO->count(); ++i) {
2546                         if (fontModule->fontsSansCO->itemText(i) == toqstr(bp_.fontsSans)) {
2547                                 fontModule->fontsSansCO->setCurrentIndex(i);
2548                                 return;
2549                         }
2550                 }
2551                 for (int i = 0; i < fontModule->fontsTypewriterCO->count(); ++i) {
2552                         if (fontModule->fontsTypewriterCO->itemText(i) == 
2553                                 toqstr(bp_.fontsTypewriter)) {
2554                                 fontModule->fontsTypewriterCO->setCurrentIndex(i);
2555                                 return;
2556                         }
2557                 }
2558         } else {
2559                 fontModule->fontencLA->setEnabled(true);
2560                 fontModule->fontencCO->setEnabled(true);
2561                 fontModule->fontencLE->setEnabled(true);
2562                 int n = findToken(tex_fonts_roman, bp_.fontsRoman);
2563                 if (n >= 0) {
2564                         fontModule->fontsRomanCO->setCurrentIndex(n);
2565                         romanChanged(n);
2566                 }
2567         
2568                 n = findToken(tex_fonts_sans, bp_.fontsSans);
2569                 if (n >= 0) {
2570                         fontModule->fontsSansCO->setCurrentIndex(n);
2571                         sansChanged(n);
2572                 }
2573         
2574                 n = findToken(tex_fonts_monospaced, bp_.fontsTypewriter);
2575                 if (n >= 0) {
2576                         fontModule->fontsTypewriterCO->setCurrentIndex(n);
2577                         ttChanged(n);
2578                 }
2579         }
2580
2581         if (!bp_.fontsCJK.empty())
2582                 fontModule->cjkFontLE->setText(
2583                         toqstr(bp_.fontsCJK));
2584         else
2585                 fontModule->cjkFontLE->setText(QString());
2586
2587         fontModule->fontScCB->setChecked(bp_.fontsSC);
2588         fontModule->fontOsfCB->setChecked(bp_.fontsOSF);
2589         fontModule->scaleSansSB->setValue(bp_.fontsSansScale);
2590         fontModule->scaleTypewriterSB->setValue(bp_.fontsTypewriterScale);
2591
2592         int nn = findToken(GuiDocument::fontfamilies, bp_.fontsDefaultFamily);
2593         if (nn >= 0)
2594                 fontModule->fontsDefaultCO->setCurrentIndex(nn);
2595
2596         if (bp_.fontenc == "global")
2597                 fontModule->fontencCO->setCurrentIndex(0);
2598         else if (bp_.fontenc == "default")
2599                 fontModule->fontencCO->setCurrentIndex(2);
2600         else {
2601                 fontModule->fontencCO->setCurrentIndex(1);
2602                 fontModule->fontencLE->setText(toqstr(bp_.fontenc));
2603         }
2604
2605         // paper
2606         bool const extern_geometry =
2607                 documentClass().provides("geometry");
2608         int const psize = bp_.papersize;
2609         pageLayoutModule->papersizeCO->setCurrentIndex(psize);
2610         setCustomPapersize(!extern_geometry && psize == 1);
2611         pageLayoutModule->papersizeCO->setEnabled(!extern_geometry);
2612
2613         bool const landscape =
2614                 bp_.orientation == ORIENTATION_LANDSCAPE;
2615         pageLayoutModule->landscapeRB->setChecked(landscape);
2616         pageLayoutModule->portraitRB->setChecked(!landscape);
2617         pageLayoutModule->landscapeRB->setEnabled(!extern_geometry);
2618         pageLayoutModule->portraitRB->setEnabled(!extern_geometry);
2619
2620         pageLayoutModule->facingPagesCB->setChecked(
2621                 bp_.sides == TwoSides);
2622
2623         pageLayoutModule->backgroundPB->setStyleSheet(
2624                 colorButtonStyleSheet(rgb2qcolor(bp_.backgroundcolor)));
2625         set_backgroundcolor = bp_.backgroundcolor;
2626
2627         lengthToWidgets(pageLayoutModule->paperwidthLE,
2628                 pageLayoutModule->paperwidthUnitCO, bp_.paperwidth, defaultUnit);
2629         lengthToWidgets(pageLayoutModule->paperheightLE,
2630                 pageLayoutModule->paperheightUnitCO, bp_.paperheight, defaultUnit);
2631
2632         // margins
2633         Ui::MarginsUi * m = marginsModule;
2634
2635         setMargins(!bp_.use_geometry);
2636
2637         lengthToWidgets(m->topLE, m->topUnit,
2638                 bp_.topmargin, defaultUnit);
2639
2640         lengthToWidgets(m->bottomLE, m->bottomUnit,
2641                 bp_.bottommargin, defaultUnit);
2642
2643         lengthToWidgets(m->innerLE, m->innerUnit,
2644                 bp_.leftmargin, defaultUnit);
2645
2646         lengthToWidgets(m->outerLE, m->outerUnit,
2647                 bp_.rightmargin, defaultUnit);
2648
2649         lengthToWidgets(m->headheightLE, m->headheightUnit,
2650                 bp_.headheight, defaultUnit);
2651
2652         lengthToWidgets(m->headsepLE, m->headsepUnit,
2653                 bp_.headsep, defaultUnit);
2654
2655         lengthToWidgets(m->footskipLE, m->footskipUnit,
2656                 bp_.footskip, defaultUnit);
2657
2658         lengthToWidgets(m->columnsepLE, m->columnsepUnit,
2659                 bp_.columnsep, defaultUnit);
2660
2661         // branches
2662         updateUnknownBranches();
2663         branchesModule->update(bp_);
2664
2665         // PDF support
2666         PDFOptions const & pdf = bp_.pdfoptions();
2667         pdfSupportModule->use_hyperrefGB->setChecked(pdf.use_hyperref);
2668         pdfSupportModule->titleLE->setText(toqstr(pdf.title));
2669         pdfSupportModule->authorLE->setText(toqstr(pdf.author));
2670         pdfSupportModule->subjectLE->setText(toqstr(pdf.subject));
2671         pdfSupportModule->keywordsLE->setText(toqstr(pdf.keywords));
2672
2673         pdfSupportModule->bookmarksGB->setChecked(pdf.bookmarks);
2674         pdfSupportModule->bookmarksnumberedCB->setChecked(pdf.bookmarksnumbered);
2675         pdfSupportModule->bookmarksopenGB->setChecked(pdf.bookmarksopen);
2676
2677         pdfSupportModule->bookmarksopenlevelSB->setValue(pdf.bookmarksopenlevel);
2678
2679         pdfSupportModule->breaklinksCB->setChecked(pdf.breaklinks);
2680         pdfSupportModule->pdfborderCB->setChecked(pdf.pdfborder);
2681         pdfSupportModule->pdfusetitleCB->setChecked(pdf.pdfusetitle);
2682         pdfSupportModule->colorlinksCB->setChecked(pdf.colorlinks);
2683
2684         nn = findToken(backref_opts, pdf.backref);
2685         if (nn >= 0)
2686                 pdfSupportModule->backrefCO->setCurrentIndex(nn);
2687
2688         pdfSupportModule->fullscreenCB->setChecked
2689                 (pdf.pagemode == pdf.pagemode_fullscreen);
2690
2691         pdfSupportModule->optionsLE->setText(
2692                 toqstr(pdf.quoted_options));
2693
2694         // Make sure that the bc is in the INITIAL state
2695         if (bc().policy().buttonStatus(ButtonPolicy::RESTORE))
2696                 bc().restore();
2697
2698         // clear changed branches cache
2699         changedBranches_.clear();
2700 }
2701
2702
2703 void GuiDocument::saveDocDefault()
2704 {
2705         // we have to apply the params first
2706         applyView();
2707         saveAsDefault();
2708 }
2709
2710
2711 void GuiDocument::updateAvailableModules() 
2712 {
2713         modules_av_model_.clear();
2714         list<modInfoStruct> const & modInfoList = getModuleInfo();
2715         list<modInfoStruct>::const_iterator mit = modInfoList.begin();
2716         list<modInfoStruct>::const_iterator men = modInfoList.end();
2717         for (int i = 0; mit != men; ++mit, ++i)
2718                 modules_av_model_.insertRow(i, mit->name, mit->id, 
2719                                 mit->description);
2720 }
2721
2722
2723 void GuiDocument::updateSelectedModules() 
2724 {
2725         modules_sel_model_.clear();
2726         list<modInfoStruct> const selModList = getSelectedModules();
2727         list<modInfoStruct>::const_iterator mit = selModList.begin();
2728         list<modInfoStruct>::const_iterator men = selModList.end();
2729         for (int i = 0; mit != men; ++mit, ++i)
2730                 modules_sel_model_.insertRow(i, mit->name, mit->id, 
2731                                 mit->description);
2732 }
2733
2734
2735 void GuiDocument::updateIncludeonlys()
2736 {
2737         masterChildModule->childrenTW->clear();
2738         QString const no = qt_("No");
2739         QString const yes = qt_("Yes");
2740
2741         if (includeonlys_.empty()) {
2742                 masterChildModule->includeallRB->setChecked(true);
2743                 masterChildModule->childrenTW->setEnabled(false);
2744                 masterChildModule->maintainAuxCB->setEnabled(false);
2745         } else {
2746                 masterChildModule->includeonlyRB->setChecked(true);
2747                 masterChildModule->childrenTW->setEnabled(true);
2748                 masterChildModule->maintainAuxCB->setEnabled(true);
2749         }
2750         QTreeWidgetItem * item = 0;
2751         std::vector<Buffer *> children = buffer().getChildren(false);
2752         vector<Buffer *>::const_iterator it  = children.begin();
2753         vector<Buffer *>::const_iterator end = children.end();
2754         bool has_unincluded = false;
2755         bool all_unincluded = true;
2756         for (; it != end; ++it) {
2757                 item = new QTreeWidgetItem(masterChildModule->childrenTW);
2758                 // FIXME Unicode
2759                 string const name =
2760                         to_utf8(makeRelPath(from_utf8((*it)->fileName().absFilename()),
2761                                                         from_utf8(buffer().filePath())));
2762                 item->setText(0, toqstr(name));
2763                 item->setText(1, isChildIncluded(name) ? yes : no);
2764                 if (!isChildIncluded(name))
2765                         has_unincluded = true;
2766                 else
2767                         all_unincluded = false;
2768         }
2769         // Both if all childs are included and if none is included
2770         // is equal to "include all" (i.e., ommit \includeonly).
2771         // Thus, reset the GUI.
2772         if (!has_unincluded || all_unincluded) {
2773                 masterChildModule->includeallRB->setChecked(true);
2774                 masterChildModule->childrenTW->setEnabled(false);
2775                 includeonlys_.clear();
2776         }
2777         // If all are included, we need to update again.
2778         if (!has_unincluded)
2779                 updateIncludeonlys();
2780 }
2781
2782
2783 void GuiDocument::updateContents()
2784 {
2785         // Nothing to do here as the document settings is not cursor dependant.
2786         return;
2787 }
2788
2789
2790 void GuiDocument::useClassDefaults()
2791 {
2792         if (applyPB->isEnabled()) {
2793                 int const ret = Alert::prompt(_("Unapplied changes"),
2794                                 _("Some changes in the dialog were not yet applied.\n"
2795                                   "If you do not apply now, they will be lost after this action."),
2796                                 1, 1, _("&Apply"), _("&Dismiss"));
2797                 if (ret == 0)
2798                         applyView();
2799         }
2800
2801         int idx = latexModule->classCO->currentIndex();
2802         string const classname = classes_model_.getIDString(idx);
2803         if (!bp_.setBaseClass(classname)) {
2804                 Alert::error(_("Error"), _("Unable to set document class."));
2805                 return;
2806         }
2807         bp_.useClassDefaults();
2808         paramsToDialog();
2809 }
2810
2811
2812 void GuiDocument::setLayoutComboByIDString(string const & idString)
2813 {
2814         int idx = classes_model_.findIDString(idString);
2815         if (idx < 0)
2816                 Alert::warning(_("Can't set layout!"), 
2817                         bformat(_("Unable to set layout for ID: %1$s"), from_utf8(idString)));
2818         else 
2819                 latexModule->classCO->setCurrentIndex(idx);
2820 }
2821
2822
2823 bool GuiDocument::isValid()
2824 {
2825         return validateListingsParameters().isEmpty()
2826                 && (textLayoutModule->skipCO->currentIndex() != 3
2827                         || !textLayoutModule->skipLE->text().isEmpty()
2828                         || textLayoutModule->indentRB->isChecked())
2829                 && (textLayoutModule->indentCO->currentIndex() != 1
2830                         || !textLayoutModule->indentLE->text().isEmpty()
2831                         || textLayoutModule->skipRB->isChecked());
2832 }
2833
2834
2835 char const * const GuiDocument::fontfamilies[5] = {
2836         "default", "rmdefault", "sfdefault", "ttdefault", ""
2837 };
2838
2839
2840 char const * GuiDocument::fontfamilies_gui[5] = {
2841         N_("Default"), N_("Roman"), N_("Sans Serif"), N_("Typewriter"), ""
2842 };
2843
2844
2845 bool GuiDocument::initialiseParams(string const &)
2846 {
2847         BufferView const * view = bufferview();
2848         if (!view) {
2849                 bp_ = BufferParams();
2850                 paramsToDialog();
2851                 return true;
2852         }
2853         bp_ = view->buffer().params();
2854         loadModuleInfo();
2855         updateAvailableModules();
2856         //FIXME It'd be nice to make sure here that the selected
2857         //modules are consistent: That required modules are actually
2858         //selected, and that we don't have conflicts. If so, we could
2859         //at least pop up a warning.
2860         paramsToDialog();
2861         return true;
2862 }
2863
2864
2865 void GuiDocument::clearParams()
2866 {
2867         bp_ = BufferParams();
2868 }
2869
2870
2871 BufferId GuiDocument::id() const
2872 {
2873         BufferView const * const view = bufferview();
2874         return view? &view->buffer() : 0;
2875 }
2876
2877
2878 list<GuiDocument::modInfoStruct> const & GuiDocument::getModuleInfo()
2879 {
2880         return moduleNames_;
2881 }
2882
2883
2884 list<GuiDocument::modInfoStruct> const 
2885                 GuiDocument::makeModuleInfo(LayoutModuleList const & mods)
2886 {
2887         LayoutModuleList::const_iterator it =  mods.begin();
2888         LayoutModuleList::const_iterator end = mods.end();
2889         list<modInfoStruct> mInfo;
2890         for (; it != end; ++it) {
2891                 modInfoStruct m;
2892                 m.id = *it;
2893                 LyXModule const * const mod = theModuleList[*it];
2894                 if (mod)
2895                         // FIXME Unicode
2896                         m.name = toqstr(translateIfPossible(from_utf8(mod->getName())));
2897                 else 
2898                         m.name = toqstr(*it) + toqstr(" (") + qt_("Not Found") + toqstr(")");
2899                 mInfo.push_back(m);
2900         }
2901         return mInfo;
2902 }
2903
2904
2905 list<GuiDocument::modInfoStruct> const GuiDocument::getSelectedModules()
2906 {
2907         return makeModuleInfo(params().getModules());
2908 }
2909
2910
2911 list<GuiDocument::modInfoStruct> const GuiDocument::getProvidedModules()
2912 {
2913         return makeModuleInfo(params().baseClass()->providedModules());
2914 }
2915
2916
2917 DocumentClass const & GuiDocument::documentClass() const
2918 {
2919         return bp_.documentClass();
2920 }
2921
2922
2923 static void dispatch_bufferparams(Dialog const & dialog,
2924         BufferParams const & bp, FuncCode lfun)
2925 {
2926         ostringstream ss;
2927         ss << "\\begin_header\n";
2928         bp.writeFile(ss);
2929         ss << "\\end_header\n";
2930         dialog.dispatch(FuncRequest(lfun, ss.str()));
2931 }
2932
2933
2934 void GuiDocument::dispatchParams()
2935 {
2936         // This must come first so that a language change is correctly noticed
2937         setLanguage();
2938
2939         // Apply the BufferParams. Note that this will set the base class
2940         // and then update the buffer's layout.
2941         dispatch_bufferparams(*this, params(), LFUN_BUFFER_PARAMS_APPLY);
2942
2943         if (!params().master.empty()) {
2944                 FileName const master_file = support::makeAbsPath(params().master,
2945                            support::onlyPath(buffer().absFileName()));
2946                 if (isLyXFilename(master_file.absFilename())) {
2947                         Buffer * master = checkAndLoadLyXFile(master_file);
2948                         if (master) {
2949                                 if (master->isChild(const_cast<Buffer *>(&buffer())))
2950                                         const_cast<Buffer &>(buffer()).setParent(master);
2951                                 else
2952                                         Alert::warning(_("Assigned master does not include this file"), 
2953                                                 bformat(_("You must include this file in the document\n"
2954                                                           "'%1$s' in order to use the master document\n"
2955                                                           "feature."), from_utf8(params().master)));
2956                         } else
2957                                 Alert::warning(_("Could not load master"), 
2958                                                 bformat(_("The master document '%1$s'\n"
2959                                                            "could not be loaded."),
2960                                                            from_utf8(params().master)));
2961                 }
2962         }
2963
2964         // Generate the colours requested by each new branch.
2965         BranchList & branchlist = params().branchlist();
2966         if (!branchlist.empty()) {
2967                 BranchList::const_iterator it = branchlist.begin();
2968                 BranchList::const_iterator const end = branchlist.end();
2969                 for (; it != end; ++it) {
2970                         docstring const & current_branch = it->branch();
2971                         Branch const * branch = branchlist.find(current_branch);
2972                         string const x11hexname = X11hexname(branch->color());
2973                         // display the new color
2974                         docstring const str = current_branch + ' ' + from_ascii(x11hexname);
2975                         dispatch(FuncRequest(LFUN_SET_COLOR, str));
2976                 }
2977
2978                 // Open insets of selected branches, close deselected ones
2979                 dispatch(FuncRequest(LFUN_ALL_INSETS_TOGGLE,
2980                         "assign branch"));
2981         }
2982         // rename branches in the document
2983         executeBranchRenaming();
2984         // and clear changed branches cache
2985         changedBranches_.clear();
2986         
2987         // Generate the colours requested by indices.
2988         IndicesList & indiceslist = params().indiceslist();
2989         if (!indiceslist.empty()) {
2990                 IndicesList::const_iterator it = indiceslist.begin();
2991                 IndicesList::const_iterator const end = indiceslist.end();
2992                 for (; it != end; ++it) {
2993                         docstring const & current_index = it->shortcut();
2994                         Index const * index = indiceslist.findShortcut(current_index);
2995                         string const x11hexname = X11hexname(index->color());
2996                         // display the new color
2997                         docstring const str = current_index + ' ' + from_ascii(x11hexname);
2998                         dispatch(FuncRequest(LFUN_SET_COLOR, str));
2999                 }
3000         }
3001         // FIXME: If we used an LFUN, we would not need those two lines:
3002         BufferView * bv = const_cast<BufferView *>(bufferview());
3003         bv->processUpdateFlags(Update::Force | Update::FitCursor);
3004 }
3005
3006
3007 void GuiDocument::setLanguage() const
3008 {
3009         Language const * const newL = bp_.language;
3010         if (buffer().params().language == newL)
3011                 return;
3012
3013         string const & lang_name = newL->lang();
3014         dispatch(FuncRequest(LFUN_BUFFER_LANGUAGE, lang_name));
3015 }
3016
3017
3018 void GuiDocument::saveAsDefault() const
3019 {
3020         dispatch_bufferparams(*this, params(), LFUN_BUFFER_SAVE_AS_DEFAULT);
3021 }
3022
3023
3024 bool GuiDocument::isFontAvailable(string const & font) const
3025 {
3026         if (font == "default" || font == "cmr"
3027             || font == "cmss" || font == "cmtt")
3028                 // these are standard
3029                 return true;
3030         if (font == "lmodern" || font == "lmss" || font == "lmtt")
3031                 return LaTeXFeatures::isAvailable("lmodern");
3032         if (font == "times" || font == "palatino"
3033                  || font == "helvet" || font == "courier")
3034                 return LaTeXFeatures::isAvailable("psnfss");
3035         if (font == "cmbr" || font == "cmtl")
3036                 return LaTeXFeatures::isAvailable("cmbright");
3037         if (font == "utopia")
3038                 return LaTeXFeatures::isAvailable("utopia")
3039                         || LaTeXFeatures::isAvailable("fourier");
3040         if (font == "beraserif" || font == "berasans"
3041                 || font == "beramono")
3042                 return LaTeXFeatures::isAvailable("bera");
3043         return LaTeXFeatures::isAvailable(font);
3044 }
3045
3046
3047 bool GuiDocument::providesOSF(string const & font) const
3048 {
3049         if (outputModule->xetexCB->isChecked())
3050                 // FIXME: we should check if the fonts really
3051                 // have OSF support. But how?
3052                 return true;
3053         if (font == "cmr")
3054                 return isFontAvailable("eco");
3055         if (font == "palatino")
3056                 return isFontAvailable("mathpazo");
3057         return false;
3058 }
3059
3060
3061 bool GuiDocument::providesSC(string const & font) const
3062 {
3063         if (outputModule->xetexCB->isChecked())
3064                 return false;
3065         if (font == "palatino")
3066                 return isFontAvailable("mathpazo");
3067         if (font == "utopia")
3068                 return isFontAvailable("fourier");
3069         return false;
3070 }
3071
3072
3073 bool GuiDocument::providesScale(string const & font) const
3074 {
3075         if (outputModule->xetexCB->isChecked())
3076                 return true;
3077         return font == "helvet" || font == "luximono"
3078                 || font == "berasans"  || font == "beramono";
3079 }
3080
3081
3082 void GuiDocument::loadModuleInfo()
3083 {
3084         moduleNames_.clear();
3085         LyXModuleList::const_iterator it  = theModuleList.begin();
3086         LyXModuleList::const_iterator end = theModuleList.end();
3087         for (; it != end; ++it) {
3088                 modInfoStruct m;
3089                 m.id = it->getID();
3090                 // FIXME Unicode
3091                 m.name = toqstr(translateIfPossible(from_utf8(it->getName())));
3092                 // this is supposed to give us the first sentence of the description
3093                 // FIXME Unicode
3094                 QString desc =
3095                         toqstr(translateIfPossible(from_utf8(it->getDescription())));
3096                 int const pos = desc.indexOf(".");
3097                 if (pos > 0)
3098                         desc.truncate(pos + 1);
3099                 m.description = desc;
3100                 moduleNames_.push_back(m);
3101         }
3102 }
3103
3104
3105 void GuiDocument::updateUnknownBranches()
3106 {
3107         if (!bufferview())
3108                 return;
3109         list<docstring> used_branches;
3110         buffer().getUsedBranches(used_branches);
3111         list<docstring>::const_iterator it = used_branches.begin();
3112         QStringList unknown_branches;
3113         for (; it != used_branches.end() ; ++it) {
3114                 if (!buffer().params().branchlist().find(*it))
3115                         unknown_branches.append(toqstr(*it));
3116         }
3117         branchesModule->setUnknownBranches(unknown_branches);
3118 }
3119
3120
3121 void GuiDocument::branchesRename(docstring const & oldname, docstring const & newname)
3122 {
3123         map<docstring, docstring>::iterator it = changedBranches_.begin();
3124         for (; it != changedBranches_.end() ; ++it) {
3125                 if (it->second == oldname) {
3126                         // branch has already been renamed
3127                         it->second = newname;
3128                         return;
3129                 }
3130         }
3131         // store new name
3132         changedBranches_[oldname] = newname;
3133 }
3134
3135
3136 void GuiDocument::executeBranchRenaming() const
3137 {
3138         map<docstring, docstring>::const_iterator it = changedBranches_.begin();
3139         for (; it != changedBranches_.end() ; ++it) {
3140                 docstring const arg = '"' + it->first + '"' + " " + '"' + it->second + '"';
3141                 dispatch(FuncRequest(LFUN_BRANCHES_RENAME, arg));
3142         }
3143 }
3144
3145
3146 Dialog * createGuiDocument(GuiView & lv) { return new GuiDocument(lv); }
3147
3148
3149 } // namespace frontend
3150 } // namespace lyx
3151
3152 #include "moc_GuiDocument.cpp"