]> git.lyx.org Git - lyx.git/blob - src/bufferparams.C
Fix bug 2485 and crash on middle mouse paste on math
[lyx.git] / src / bufferparams.C
1 /**
2  * \file bufferparams.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author John Levon
10  * \author André Pönitz
11  * \author Martin Vermeer
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "bufferparams.h"
19
20 #include "author.h"
21 #include "BranchList.h"
22 #include "Bullet.h"
23 #include "debug.h"
24 #include "encoding.h"
25 #include "gettext.h"
26 #include "language.h"
27 #include "LaTeXFeatures.h"
28 #include "LColor.h"
29 #include "lyxlex.h"
30 #include "lyxrc.h"
31 #include "lyxtextclasslist.h"
32 #include "outputparams.h"
33 #include "tex-strings.h"
34 #include "Spacing.h"
35 #include "texrow.h"
36 #include "vspace.h"
37
38 #include "frontends/Alert.h"
39
40 #include "support/lyxalgo.h" // for lyx::count
41 #include "support/convert.h"
42 #include "support/translator.h"
43
44 #include <boost/array.hpp>
45
46 #include <sstream>
47
48 namespace support = lyx::support;
49 using lyx::support::bformat;
50 using lyx::support::rtrim;
51 using lyx::support::tokenPos;
52
53 using std::endl;
54 using std::string;
55 using std::istringstream;
56 using std::ostream;
57 using std::ostringstream;
58 using std::pair;
59
60 namespace biblio = lyx::biblio;
61
62
63 // Local translators
64 namespace {
65
66 // Paragraph separation
67 typedef Translator<string, BufferParams::PARSEP> ParSepTranslator;
68
69
70 ParSepTranslator const init_parseptranslator()
71 {
72         ParSepTranslator translator(string_paragraph_separation[0], BufferParams::PARSEP_INDENT);
73         translator.addPair(string_paragraph_separation[1], BufferParams::PARSEP_SKIP);
74         return translator;
75 }
76
77
78 ParSepTranslator const & parseptranslator()
79 {
80         static ParSepTranslator translator = init_parseptranslator();
81         return translator;
82 }
83
84
85 // Quotes language
86 typedef Translator<string, InsetQuotes::quote_language> QuotesLangTranslator;
87
88
89 QuotesLangTranslator const init_quoteslangtranslator()
90 {
91         QuotesLangTranslator translator(string_quotes_language[0], InsetQuotes::EnglishQ);
92         translator.addPair(string_quotes_language[1], InsetQuotes::SwedishQ);
93         translator.addPair(string_quotes_language[2], InsetQuotes::GermanQ);
94         translator.addPair(string_quotes_language[3], InsetQuotes::PolishQ);
95         translator.addPair(string_quotes_language[4], InsetQuotes::FrenchQ);
96         translator.addPair(string_quotes_language[5], InsetQuotes::DanishQ);
97         return translator;
98 }
99
100
101 QuotesLangTranslator const & quoteslangtranslator()
102 {
103         static QuotesLangTranslator translator = init_quoteslangtranslator();
104         return translator;
105 }
106
107
108 // Paper size
109 typedef Translator<std::string, PAPER_SIZE> PaperSizeTranslator;
110
111
112 PaperSizeTranslator const init_papersizetranslator()
113 {
114         PaperSizeTranslator translator(string_papersize[0], PAPER_DEFAULT);
115         translator.addPair(string_papersize[1], PAPER_CUSTOM);
116         translator.addPair(string_papersize[2], PAPER_USLETTER);
117         translator.addPair(string_papersize[3], PAPER_USLEGAL);
118         translator.addPair(string_papersize[4], PAPER_USEXECUTIVE);
119         translator.addPair(string_papersize[5], PAPER_A3);
120         translator.addPair(string_papersize[6], PAPER_A4);
121         translator.addPair(string_papersize[7], PAPER_A5);
122         translator.addPair(string_papersize[8], PAPER_B3);
123         translator.addPair(string_papersize[9], PAPER_B4);
124         translator.addPair(string_papersize[10], PAPER_B5);
125         return translator;
126 }
127
128
129 PaperSizeTranslator const & papersizetranslator()
130 {
131         static PaperSizeTranslator translator = init_papersizetranslator();
132         return translator;
133 }
134
135
136 // Paper orientation
137 typedef Translator<string, PAPER_ORIENTATION> PaperOrientationTranslator;
138
139
140 PaperOrientationTranslator const init_paperorientationtranslator()
141 {
142         PaperOrientationTranslator translator(string_orientation[0], ORIENTATION_PORTRAIT);
143         translator.addPair(string_orientation[1], ORIENTATION_LANDSCAPE);
144         return translator;
145 }
146
147
148 PaperOrientationTranslator const & paperorientationtranslator()
149 {
150         static PaperOrientationTranslator translator = init_paperorientationtranslator();
151         return translator;
152 }
153
154
155 // Page sides
156 typedef Translator<int, LyXTextClass::PageSides> SidesTranslator;
157
158
159 SidesTranslator const init_sidestranslator()
160 {
161         SidesTranslator translator(1, LyXTextClass::OneSide);
162         translator.addPair(2, LyXTextClass::TwoSides);
163         return translator;
164 }
165
166
167 SidesTranslator const & sidestranslator()
168 {
169         static SidesTranslator translator = init_sidestranslator();
170         return translator;
171 }
172
173
174
175 // AMS
176 typedef Translator<int, BufferParams::AMS> AMSTranslator;
177
178
179 AMSTranslator const init_amstranslator()
180 {
181         AMSTranslator translator(0, BufferParams::AMS_OFF);
182         translator.addPair(1, BufferParams::AMS_AUTO);
183         translator.addPair(2, BufferParams::AMS_ON);
184         return translator;
185 }
186
187
188 AMSTranslator const & amstranslator()
189 {
190         static AMSTranslator translator = init_amstranslator();
191         return translator;
192 }
193
194
195 // Cite engine
196 typedef Translator<string, biblio::CiteEngine> CiteEngineTranslator;
197
198
199 CiteEngineTranslator const init_citeenginetranslator()
200 {
201         CiteEngineTranslator translator("basic", biblio::ENGINE_BASIC);
202         translator.addPair("natbib_numerical", biblio::ENGINE_NATBIB_NUMERICAL);
203         translator.addPair("natbib_authoryear", biblio::ENGINE_NATBIB_AUTHORYEAR);
204         translator.addPair("jurabib", biblio::ENGINE_JURABIB);
205         return translator;
206 }
207
208
209 CiteEngineTranslator const & citeenginetranslator()
210 {
211         static CiteEngineTranslator translator = init_citeenginetranslator();
212         return translator;
213 }
214
215
216 // Spacing
217 typedef Translator<string, Spacing::Space> SpaceTranslator;
218
219
220 SpaceTranslator const init_spacetranslator()
221 {
222         SpaceTranslator translator("default", Spacing::Default);
223         translator.addPair("single", Spacing::Single);
224         translator.addPair("onehalf", Spacing::Onehalf);
225         translator.addPair("double", Spacing::Double);
226         translator.addPair("other", Spacing::Other);
227         return translator;
228 }
229
230
231 SpaceTranslator const & spacetranslator()
232 {
233         static SpaceTranslator translator = init_spacetranslator();
234         return translator;
235 }
236
237 // ends annonym namespace
238 }
239
240
241 class BufferParams::Impl
242 {
243 public:
244         Impl();
245
246         AuthorList authorlist;
247         BranchList branchlist;
248         boost::array<Bullet, 4> temp_bullets;
249         boost::array<Bullet, 4> user_defined_bullets;
250         Spacing spacing;
251         /** This is the amount of space used for paragraph_separation "skip",
252          * and for detached paragraphs in "indented" documents.
253          */
254         VSpace defskip;
255 };
256
257
258 BufferParams::Impl::Impl()
259         : defskip(VSpace::MEDSKIP)
260 {
261         // set initial author
262         authorlist.record(Author(lyxrc.user_name, lyxrc.user_email));
263 }
264
265
266 BufferParams::Impl *
267 BufferParams::MemoryTraits::clone(BufferParams::Impl const * ptr)
268 {
269         BOOST_ASSERT(ptr);
270
271         return new BufferParams::Impl(*ptr);
272 }
273
274
275 void BufferParams::MemoryTraits::destroy(BufferParams::Impl * ptr)
276 {
277         delete ptr;
278 }
279
280
281 BufferParams::BufferParams()
282         : // Initialize textclass to point to article. if `first' is
283           // true in the returned pair, then `second' is the textclass
284           // number; if it is false, second is 0. In both cases, second
285           // is what we want.
286         textclass(textclasslist.numberOfClass("article").second),
287         pimpl_(new Impl)
288 {
289         paragraph_separation = PARSEP_INDENT;
290         quotes_language = InsetQuotes::EnglishQ;
291         fontsize = "default";
292
293         /*  PaperLayout */
294         papersize = PAPER_DEFAULT;
295         orientation = ORIENTATION_PORTRAIT;
296         use_geometry = false;
297         use_amsmath = AMS_AUTO;
298         cite_engine = biblio::ENGINE_BASIC;
299         use_bibtopic = false;
300         tracking_changes = false;
301         output_changes = false;
302         secnumdepth = 3;
303         tocdepth = 3;
304         language = default_language;
305         fonts = "default";
306         inputenc = "auto";
307         graphicsDriver = "default";
308         sides = LyXTextClass::OneSide;
309         columns = 1;
310         pagestyle = "default";
311         compressed = false;
312         for (int iter = 0; iter < 4; ++iter) {
313                 user_defined_bullet(iter) = ITEMIZE_DEFAULTS[iter];
314                 temp_bullet(iter) = ITEMIZE_DEFAULTS[iter];
315         }
316 }
317
318
319 BufferParams::~BufferParams()
320 {}
321
322
323 AuthorList & BufferParams::authors()
324 {
325         return pimpl_->authorlist;
326 }
327
328
329 AuthorList const & BufferParams::authors() const
330 {
331         return pimpl_->authorlist;
332 }
333
334
335 BranchList & BufferParams::branchlist()
336 {
337         return pimpl_->branchlist;
338 }
339
340
341 BranchList const & BufferParams::branchlist() const
342 {
343         return pimpl_->branchlist;
344 }
345
346
347 Bullet & BufferParams::temp_bullet(lyx::size_type const index)
348 {
349         BOOST_ASSERT(index < 4);
350         return pimpl_->temp_bullets[index];
351 }
352
353
354 Bullet const & BufferParams::temp_bullet(lyx::size_type const index) const
355 {
356         BOOST_ASSERT(index < 4);
357         return pimpl_->temp_bullets[index];
358 }
359
360
361 Bullet & BufferParams::user_defined_bullet(lyx::size_type const index)
362 {
363         BOOST_ASSERT(index < 4);
364         return pimpl_->user_defined_bullets[index];
365 }
366
367
368 Bullet const & BufferParams::user_defined_bullet(lyx::size_type const index) const
369 {
370         BOOST_ASSERT(index < 4);
371         return pimpl_->user_defined_bullets[index];
372 }
373
374
375 Spacing & BufferParams::spacing()
376 {
377         return pimpl_->spacing;
378 }
379
380
381 Spacing const & BufferParams::spacing() const
382 {
383         return pimpl_->spacing;
384 }
385
386
387 VSpace const & BufferParams::getDefSkip() const
388 {
389         return pimpl_->defskip;
390 }
391
392
393 void BufferParams::setDefSkip(VSpace const & vs)
394 {
395         pimpl_->defskip = vs;
396 }
397
398
399 string const BufferParams::readToken(LyXLex & lex, string const & token)
400 {
401         if (token == "\\textclass") {
402                 lex.next();
403                 string const classname = lex.getString();
404                 pair<bool, lyx::textclass_type> pp =
405                         textclasslist.numberOfClass(classname);
406                 if (pp.first) {
407                         textclass = pp.second;
408                 } else {
409                         // if text class does not exist, try to load it from filepath
410                         pp = textclasslist.addTextClass(classname, filepath);
411                         if (pp.first) {
412                                 textclass = pp.second;
413                         } else {        
414                                 textclass = 0;
415                                 return classname;
416                         }       
417                 }
418                 // FIXME: isTeXClassAvailable will try to load the layout file, but will
419                 // fail because of the lack of path info. Warnings will be given although
420                 // the layout file will be correctly loaded later.
421                 if (!getLyXTextClass().isTeXClassAvailable()) {
422                         string const msg =
423                                 bformat(_("The document uses a missing "
424                                 "TeX class \"%1$s\".\n"), classname);
425                         Alert::warning(_("Document class not available"),
426                                        msg + _("LyX will not be able to produce output."));
427                 }
428         } else if (token == "\\begin_preamble") {
429                 readPreamble(lex);
430         } else if (token == "\\options") {
431                 lex.eatLine();
432                 options = lex.getString();
433         } else if (token == "\\language") {
434                 readLanguage(lex);
435         } else if (token == "\\inputencoding") {
436                 lex >> inputenc;
437         } else if (token == "\\graphics") {
438                 readGraphicsDriver(lex);
439         } else if (token == "\\fontscheme") {
440                 lex >> fonts;
441         } else if (token == "\\paragraph_separation") {
442                 string parsep;
443                 lex >> parsep;
444                 paragraph_separation = parseptranslator().find(parsep);
445         } else if (token == "\\defskip") {
446                 lex.next();
447                 pimpl_->defskip = VSpace(lex.getString());
448         } else if (token == "\\quotes_language") {
449                 string quotes_lang;
450                 lex >> quotes_lang;
451                 quotes_language = quoteslangtranslator().find(quotes_lang);
452         } else if (token == "\\papersize") {
453                 string ppsize;
454                 lex >> ppsize;
455                 papersize = papersizetranslator().find(ppsize);
456         } else if (token == "\\use_geometry") {
457                 lex >> use_geometry;
458         } else if (token == "\\use_amsmath") {
459                 int use_ams;
460                 lex >> use_ams;
461                 use_amsmath = amstranslator().find(use_ams);
462         } else if (token == "\\cite_engine") {
463                 string engine;
464                 lex >> engine;
465                 cite_engine = citeenginetranslator().find(engine);
466         } else if (token == "\\use_bibtopic") {
467                 lex >> use_bibtopic;
468         } else if (token == "\\tracking_changes") {
469                 lex >> tracking_changes;
470         } else if (token == "\\output_changes") {
471                 lex >> output_changes;
472         } else if (token == "\\branch") {
473                 lex.next();
474                 string branch = lex.getString();
475                 branchlist().add(branch);
476                 while (true) {
477                         lex.next();
478                         string const tok = lex.getString();
479                         if (tok == "\\end_branch")
480                                 break;
481                         Branch * branch_ptr = branchlist().find(branch);
482                         if (tok == "\\selected") {
483                                 lex.next();
484                                 if (branch_ptr)
485                                         branch_ptr->setSelected(lex.getInteger());
486                         }
487                         // not yet operational
488                         if (tok == "\\color") {
489                                 lex.eatLine();
490                                 string color = lex.getString();
491                                 if (branch_ptr)
492                                         branch_ptr->setColor(color);
493                                 // Update also the LColor table:
494                                 if (color == "none")
495                                         color = lcolor.getX11Name(LColor::background);
496                                 lcolor.setColor(branch, color);
497
498                         }
499                 }
500         } else if (token == "\\author") {
501                 lex.eatLine();
502                 istringstream ss(lex.getString());
503                 Author a;
504                 ss >> a;
505                 author_map.push_back(pimpl_->authorlist.record(a));
506         } else if (token == "\\paperorientation") {
507                 string orient;
508                 lex >> orient;
509                 orientation = paperorientationtranslator().find(orient);
510         } else if (token == "\\paperwidth") {
511                 lex >> paperwidth;
512         } else if (token == "\\paperheight") {
513                 lex >> paperheight;
514         } else if (token == "\\leftmargin") {
515                 lex >> leftmargin;
516         } else if (token == "\\topmargin") {
517                 lex >> topmargin;
518         } else if (token == "\\rightmargin") {
519                 lex >> rightmargin;
520         } else if (token == "\\bottommargin") {
521                 lex >> bottommargin;
522         } else if (token == "\\headheight") {
523                 lex >> headheight;
524         } else if (token == "\\headsep") {
525                 lex >> headsep;
526         } else if (token == "\\footskip") {
527                 lex >> footskip;
528         } else if (token == "\\paperfontsize") {
529                 lex >> fontsize;
530         } else if (token == "\\papercolumns") {
531                 lex >> columns;
532         } else if (token == "\\papersides") {
533                 int psides;
534                 lex >> psides;
535                 sides = sidestranslator().find(psides);
536         } else if (token == "\\paperpagestyle") {
537                 lex >> pagestyle;
538         } else if (token == "\\bullet") {
539                 readBullets(lex);
540         } else if (token == "\\bulletLaTeX") {
541                 readBulletsLaTeX(lex);
542         } else if (token == "\\secnumdepth") {
543                 lex >> secnumdepth;
544         } else if (token == "\\tocdepth") {
545                 lex >> tocdepth;
546         } else if (token == "\\spacing") {
547                 string nspacing;
548                 lex >> nspacing;
549                 string tmp_val;
550                 if (nspacing == "other") {
551                         lex >> tmp_val;
552                 }
553                 spacing().set(spacetranslator().find(nspacing), tmp_val);
554         } else if (token == "\\float_placement") {
555                 lex >> float_placement;
556         } else {
557                 return token;
558         }
559
560         return string();
561 }
562
563
564 void BufferParams::writeFile(ostream & os) const
565 {
566         // The top of the file is written by the buffer.
567         // Prints out the buffer info into the .lyx file given by file
568
569         // the textclass
570         os << "\\textclass " << textclasslist[textclass].name() << '\n';
571
572         // then the the preamble
573         if (!preamble.empty()) {
574                 // remove '\n' from the end of preamble
575                 string const tmppreamble = rtrim(preamble, "\n");
576                 os << "\\begin_preamble\n"
577                    << tmppreamble
578                    << "\n\\end_preamble\n";
579         }
580
581         // the options
582         if (!options.empty()) {
583                 os << "\\options " << options << '\n';
584         }
585
586         // then the text parameters
587         if (language != ignore_language)
588                 os << "\\language " << language->lang() << '\n';
589         os << "\\inputencoding " << inputenc
590            << "\n\\fontscheme " << fonts
591            << "\n\\graphics " << graphicsDriver << '\n';
592
593         if (!float_placement.empty()) {
594                 os << "\\float_placement " << float_placement << '\n';
595         }
596         os << "\\paperfontsize " << fontsize << '\n';
597
598         spacing().writeFile(os);
599
600         os << "\\papersize " << string_papersize[papersize]
601            << "\n\\use_geometry " << convert<string>(use_geometry)
602            << "\n\\use_amsmath " << use_amsmath
603            << "\n\\cite_engine " << citeenginetranslator().find(cite_engine)
604            << "\n\\use_bibtopic " << convert<string>(use_bibtopic)
605            << "\n\\paperorientation " << string_orientation[orientation]
606            << '\n';
607
608         BranchList::const_iterator it = branchlist().begin();
609         BranchList::const_iterator end = branchlist().end();
610         for (; it != end; ++it) {
611                 os << "\\branch " << it->getBranch()
612                    << "\n\\selected " << it->getSelected()
613                    << "\n\\color " << lyx::X11hexname(it->getColor())
614                    << "\n\\end_branch"
615                    << "\n";
616         }
617
618         if (!paperwidth.empty())
619                 os << "\\paperwidth "
620                    << VSpace(paperwidth).asLyXCommand() << '\n';
621         if (!paperheight.empty())
622                 os << "\\paperheight "
623                    << VSpace(paperheight).asLyXCommand() << '\n';
624         if (!leftmargin.empty())
625                 os << "\\leftmargin "
626                    << VSpace(leftmargin).asLyXCommand() << '\n';
627         if (!topmargin.empty())
628                 os << "\\topmargin "
629                    << VSpace(topmargin).asLyXCommand() << '\n';
630         if (!rightmargin.empty())
631                 os << "\\rightmargin "
632                    << VSpace(rightmargin).asLyXCommand() << '\n';
633         if (!bottommargin.empty())
634                 os << "\\bottommargin "
635                    << VSpace(bottommargin).asLyXCommand() << '\n';
636         if (!headheight.empty())
637                 os << "\\headheight "
638                    << VSpace(headheight).asLyXCommand() << '\n';
639         if (!headsep.empty())
640                 os << "\\headsep "
641                    << VSpace(headsep).asLyXCommand() << '\n';
642         if (!footskip.empty())
643                 os << "\\footskip "
644                    << VSpace(footskip).asLyXCommand() << '\n';
645         os << "\\secnumdepth " << secnumdepth
646            << "\n\\tocdepth " << tocdepth
647            << "\n\\paragraph_separation "
648            << string_paragraph_separation[paragraph_separation]
649            << "\n\\defskip " << getDefSkip().asLyXCommand()
650            << "\n\\quotes_language "
651            << string_quotes_language[quotes_language]
652            << "\n\\papercolumns " << columns
653            << "\n\\papersides " << sides
654            << "\n\\paperpagestyle " << pagestyle << '\n';
655         for (int i = 0; i < 4; ++i) {
656                 if (user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
657                         if (user_defined_bullet(i).getFont() != -1) {
658                                 os << "\\bullet " << i << " "
659                                    << user_defined_bullet(i).getFont() << " "
660                                    << user_defined_bullet(i).getCharacter() << " "
661                                    << user_defined_bullet(i).getSize() << "\n";
662                         }
663                         else {
664                                 os << "\\bulletLaTeX " << i << " \""
665                                    << user_defined_bullet(i).getText()
666                                    << "\"\n";
667                         }
668                 }
669         }
670
671         os << "\\tracking_changes " << convert<string>(tracking_changes) << "\n";
672         os << "\\output_changes " << convert<string>(output_changes) << "\n";
673
674         if (tracking_changes) {
675                 AuthorList::Authors::const_iterator it = pimpl_->authorlist.begin();
676                 AuthorList::Authors::const_iterator end = pimpl_->authorlist.end();
677                 for (; it != end; ++it) {
678                         os << "\\author " << it->second << "\n";
679                 }
680         }
681 }
682
683
684 bool BufferParams::writeLaTeX(ostream & os, LaTeXFeatures & features,
685                               TexRow & texrow) const
686 {
687         os << "\\documentclass";
688
689         LyXTextClass const & tclass = getLyXTextClass();
690
691         ostringstream clsoptions; // the document class options.
692
693         if (tokenPos(tclass.opt_fontsize(),
694                      '|', fontsize) >= 0) {
695                 // only write if existing in list (and not default)
696                 clsoptions << fontsize << "pt,";
697         }
698
699         // custom, A3, B3 and B4 paper sizes need geometry
700         bool nonstandard_papersize = (papersize == PAPER_B3) ||
701                                      (papersize == PAPER_B4) ||
702                                      (papersize == PAPER_A3) ||
703                                      (papersize == PAPER_CUSTOM);
704
705         if (!use_geometry) {
706                 switch (papersize) {
707                 case PAPER_A4:
708                         clsoptions << "a4paper,";
709                         break;
710                 case PAPER_USLETTER:
711                         clsoptions << "letterpaper,";
712                         break;
713                 case PAPER_A5:
714                         clsoptions << "a5paper,";
715                         break;
716                 case PAPER_B5:
717                         clsoptions << "b5paper,";
718                         break;
719                 case PAPER_USEXECUTIVE:
720                         clsoptions << "executivepaper,";
721                         break;
722                 case PAPER_USLEGAL:
723                         clsoptions << "legalpaper,";
724                         break;
725                 case PAPER_DEFAULT:
726                 case PAPER_A3:
727                 case PAPER_B3:
728                 case PAPER_B4:
729                 case PAPER_CUSTOM:
730                         break;
731                 }
732         }
733
734         // if needed
735         if (sides != tclass.sides()) {
736                 switch (sides) {
737                 case LyXTextClass::OneSide:
738                         clsoptions << "oneside,";
739                         break;
740                 case LyXTextClass::TwoSides:
741                         clsoptions << "twoside,";
742                         break;
743                 }
744         }
745
746         // if needed
747         if (columns != tclass.columns()) {
748                 if (columns == 2)
749                         clsoptions << "twocolumn,";
750                 else
751                         clsoptions << "onecolumn,";
752         }
753
754         if (!use_geometry
755             && orientation == ORIENTATION_LANDSCAPE)
756                 clsoptions << "landscape,";
757
758         // language should be a parameter to \documentclass
759         if (language->babel() == "hebrew"
760             && default_language->babel() != "hebrew")
761                 // This seems necessary
762                 features.useLanguage(default_language);
763
764         ostringstream language_options;
765         bool const use_babel = features.useBabel();
766         if (use_babel) {
767                 language_options << features.getLanguages();
768                 language_options << language->babel();
769                 if (lyxrc.language_global_options)
770                         clsoptions << language_options.str() << ',';
771         }
772
773         // the user-defined options
774         if (!options.empty()) {
775                 clsoptions << options << ',';
776         }
777
778         string strOptions(clsoptions.str());
779         if (!strOptions.empty()) {
780                 strOptions = rtrim(strOptions, ",");
781                 os << '[' << strOptions << ']';
782         }
783
784         os << '{' << tclass.latexname() << "}\n";
785         texrow.newline();
786         // end of \documentclass defs
787
788         // font selection must be done before loading fontenc.sty
789         // The ae package is not needed when using OT1 font encoding.
790         if (fonts != "default" &&
791             (fonts != "ae" || lyxrc.fontenc != "default")) {
792                 os << "\\usepackage{" << fonts << "}\n";
793                 texrow.newline();
794                 if (fonts == "ae") {
795                         os << "\\usepackage{aecompl}\n";
796                         texrow.newline();
797                 }
798         }
799         // this one is not per buffer
800         if (lyxrc.fontenc != "default") {
801                 os << "\\usepackage[" << lyxrc.fontenc
802                    << "]{fontenc}\n";
803                 texrow.newline();
804         }
805
806         if (inputenc == "auto") {
807                 string const doc_encoding =
808                         language->encoding()->latexName();
809
810                 // Create a list with all the input encodings used
811                 // in the document
812                 std::set<string> encodings =
813                         features.getEncodingSet(doc_encoding);
814
815                 os << "\\usepackage[";
816                 std::copy(encodings.begin(), encodings.end(),
817                           std::ostream_iterator<string>(os, ","));
818                 os << doc_encoding << "]{inputenc}\n";
819                 texrow.newline();
820         } else if (inputenc != "default") {
821                 os << "\\usepackage[" << inputenc
822                    << "]{inputenc}\n";
823                 texrow.newline();
824         }
825
826         if (use_geometry || nonstandard_papersize) {
827                 os << "\\usepackage{geometry}\n";
828                 texrow.newline();
829                 os << "\\geometry{verbose";
830                 if (orientation == ORIENTATION_LANDSCAPE)
831                         os << ",landscape";
832                 switch (papersize) {
833                 case PAPER_CUSTOM:
834                         if (!paperwidth.empty())
835                                 os << ",paperwidth="
836                                    << paperwidth;
837                         if (!paperheight.empty())
838                                 os << ",paperheight="
839                                    << paperheight;
840                         break;
841                 case PAPER_USLETTER:
842                         os << ",letterpaper";
843                         break;
844                 case PAPER_USLEGAL:
845                         os << ",legalpaper";
846                         break;
847                 case PAPER_USEXECUTIVE:
848                         os << ",executivepaper";
849                         break;
850                 case PAPER_A3:
851                         os << ",a3paper";
852                         break;
853                 case PAPER_A4:
854                         os << ",a4paper";
855                         break;
856                 case PAPER_A5:
857                         os << ",a5paper";
858                         break;
859                 case PAPER_B3:
860                         os << ",b3paper";
861                         break;
862                 case PAPER_B4:
863                         os << ",b4paper";
864                         break;
865                 case PAPER_B5:
866                         os << ",b5paper";
867                         break;
868                 default:
869                         // default papersize ie PAPER_DEFAULT
870                         switch (lyxrc.default_papersize) {
871                         case PAPER_DEFAULT: // keep compiler happy
872                         case PAPER_USLETTER:
873                                 os << ",letterpaper";
874                                 break;
875                         case PAPER_USLEGAL:
876                                 os << ",legalpaper";
877                                 break;
878                         case PAPER_USEXECUTIVE:
879                                 os << ",executivepaper";
880                                 break;
881                         case PAPER_A3:
882                                 os << ",a3paper";
883                                 break;
884                         case PAPER_A4:
885                                 os << ",a4paper";
886                                 break;
887                         case PAPER_A5:
888                                 os << ",a5paper";
889                                 break;
890                         case PAPER_B5:
891                                 os << ",b5paper";
892                                 break;
893                         case PAPER_B3:
894                         case PAPER_B4:
895                         case PAPER_CUSTOM:
896                                 break;
897                         }
898                 }
899                 if (!topmargin.empty())
900                         os << ",tmargin=" << topmargin;
901                 if (!bottommargin.empty())
902                         os << ",bmargin=" << bottommargin;
903                 if (!leftmargin.empty())
904                         os << ",lmargin=" << leftmargin;
905                 if (!rightmargin.empty())
906                         os << ",rmargin=" << rightmargin;
907                 if (!headheight.empty())
908                         os << ",headheight=" << headheight;
909                 if (!headsep.empty())
910                         os << ",headsep=" << headsep;
911                 if (!footskip.empty())
912                         os << ",footskip=" << footskip;
913                 os << "}\n";
914                 texrow.newline();
915         }
916
917         if (tokenPos(tclass.opt_pagestyle(),
918                      '|', pagestyle) >= 0) {
919                 if (pagestyle == "fancy") {
920                         os << "\\usepackage{fancyhdr}\n";
921                         texrow.newline();
922                 }
923                 os << "\\pagestyle{" << pagestyle << "}\n";
924                 texrow.newline();
925         }
926
927         // Only if class has a ToC hierarchy
928         if (tclass.hasTocLevels()) {
929                 if (secnumdepth != tclass.secnumdepth()) {
930                         os << "\\setcounter{secnumdepth}{"
931                            << secnumdepth
932                            << "}\n";
933                         texrow.newline();
934                 }
935                 if (tocdepth != tclass.tocdepth()) {
936                         os << "\\setcounter{tocdepth}{"
937                            << tocdepth
938                            << "}\n";
939                         texrow.newline();
940                 }
941         }
942
943         if (paragraph_separation) {
944                 switch (getDefSkip().kind()) {
945                 case VSpace::SMALLSKIP:
946                         os << "\\setlength\\parskip{\\smallskipamount}\n";
947                         break;
948                 case VSpace::MEDSKIP:
949                         os << "\\setlength\\parskip{\\medskipamount}\n";
950                         break;
951                 case VSpace::BIGSKIP:
952                         os << "\\setlength\\parskip{\\bigskipamount}\n";
953                         break;
954                 case VSpace::LENGTH:
955                         os << "\\setlength\\parskip{"
956                            << getDefSkip().length().asLatexString()
957                            << "}\n";
958                         break;
959                 default: // should never happen // Then delete it.
960                         os << "\\setlength\\parskip{\\medskipamount}\n";
961                         break;
962                 }
963                 texrow.newline();
964
965                 os << "\\setlength\\parindent{0pt}\n";
966                 texrow.newline();
967         }
968
969         // If we use jurabib, we have to call babel here.
970         if (use_babel && features.isRequired("jurabib")) {
971                 os << babelCall(language_options.str())
972                    << '\n'
973                    << features.getBabelOptions();
974                 texrow.newline();
975         }
976
977         // Now insert the LyX specific LaTeX commands...
978
979         // The optional packages;
980         string lyxpreamble(features.getPackages());
981
982         // this might be useful...
983         lyxpreamble += "\n\\makeatletter\n";
984
985         // Some macros LyX will need
986         string tmppreamble(features.getMacros());
987
988         if (!tmppreamble.empty()) {
989                 lyxpreamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
990                         "LyX specific LaTeX commands.\n"
991                         + tmppreamble + '\n';
992         }
993
994         // the text class specific preamble
995         tmppreamble = features.getTClassPreamble();
996         if (!tmppreamble.empty()) {
997                 lyxpreamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
998                         "Textclass specific LaTeX commands.\n"
999                         + tmppreamble + '\n';
1000         }
1001
1002         /* the user-defined preamble */
1003         if (!preamble.empty()) {
1004                 lyxpreamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1005                         "User specified LaTeX commands.\n"
1006                         + preamble + '\n';
1007         }
1008
1009         // Itemize bullet settings need to be last in case the user
1010         // defines their own bullets that use a package included
1011         // in the user-defined preamble -- ARRae
1012         // Actually it has to be done much later than that
1013         // since some packages like frenchb make modifications
1014         // at \begin{document} time -- JMarc
1015         string bullets_def;
1016         for (int i = 0; i < 4; ++i) {
1017                 if (user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1018                         if (bullets_def.empty())
1019                                 bullets_def="\\AtBeginDocument{\n";
1020                         bullets_def += "  \\def\\labelitemi";
1021                         switch (i) {
1022                                 // `i' is one less than the item to modify
1023                         case 0:
1024                                 break;
1025                         case 1:
1026                                 bullets_def += 'i';
1027                                 break;
1028                         case 2:
1029                                 bullets_def += "ii";
1030                                 break;
1031                         case 3:
1032                                 bullets_def += 'v';
1033                                 break;
1034                         }
1035                         bullets_def += '{' +
1036                                 user_defined_bullet(i).getText()
1037                                 + "}\n";
1038                 }
1039         }
1040
1041         if (!bullets_def.empty())
1042                 lyxpreamble += bullets_def + "}\n\n";
1043
1044         // We try to load babel late, in case it interferes
1045         // with other packages.
1046         // Jurabib has to be called after babel, though.
1047         if (use_babel && !features.isRequired("jurabib")) {
1048                 lyxpreamble += babelCall(language_options.str()) + '\n';
1049                 lyxpreamble += features.getBabelOptions();
1050         }
1051
1052         lyxpreamble += "\\makeatother\n";
1053
1054         // dvipost settings come after everything else
1055         if (features.isAvailable("dvipost") && tracking_changes && output_changes) {
1056                 lyxpreamble +=
1057                         "\\dvipostlayout\n"
1058                         "\\dvipost{osstart color push Red}\n"
1059                         "\\dvipost{osend color pop}\n"
1060                         "\\dvipost{cbstart color push Blue}\n"
1061                         "\\dvipost{cbend color pop}\n";
1062         }
1063
1064         int const nlines =
1065                 int(lyx::count(lyxpreamble.begin(), lyxpreamble.end(), '\n'));
1066         for (int j = 0; j != nlines; ++j) {
1067                 texrow.newline();
1068         }
1069
1070         os << lyxpreamble;
1071         return use_babel;
1072 }
1073
1074
1075 void BufferParams::useClassDefaults()
1076 {
1077         LyXTextClass const & tclass = textclasslist[textclass];
1078
1079         sides = tclass.sides();
1080         columns = tclass.columns();
1081         pagestyle = tclass.pagestyle();
1082         options = tclass.options();
1083         // Only if class has a ToC hierarchy
1084         if (tclass.hasTocLevels()) {
1085                 secnumdepth = tclass.secnumdepth();
1086                 tocdepth = tclass.tocdepth();
1087         }
1088 }
1089
1090
1091 bool BufferParams::hasClassDefaults() const
1092 {
1093         LyXTextClass const & tclass = textclasslist[textclass];
1094
1095         return (sides == tclass.sides()
1096                 && columns == tclass.columns()
1097                 && pagestyle == tclass.pagestyle()
1098                 && options == tclass.options()
1099                 && secnumdepth == tclass.secnumdepth()
1100                 && tocdepth == tclass.tocdepth());
1101 }
1102
1103
1104 LyXTextClass const & BufferParams::getLyXTextClass() const
1105 {
1106         return textclasslist[textclass];
1107 }
1108
1109
1110 LyXFont const BufferParams::getFont() const
1111 {
1112         LyXFont f = getLyXTextClass().defaultfont();
1113         f.setLanguage(language);
1114         return f;
1115 }
1116
1117
1118 void BufferParams::readPreamble(LyXLex & lex)
1119 {
1120         if (lex.getString() != "\\begin_preamble")
1121                 lyxerr << "Error (BufferParams::readPreamble):"
1122                         "consistency check failed." << endl;
1123
1124         preamble = lex.getLongString("\\end_preamble");
1125 }
1126
1127
1128 void BufferParams::readLanguage(LyXLex & lex)
1129 {
1130         if (!lex.next()) return;
1131
1132         string const tmptok = lex.getString();
1133
1134         // check if tmptok is part of tex_babel in tex-defs.h
1135         language = languages.getLanguage(tmptok);
1136         if (!language) {
1137                 // Language tmptok was not found
1138                 language = default_language;
1139                 lyxerr << "Warning: Setting language `"
1140                        << tmptok << "' to `" << language->lang()
1141                        << "'." << endl;
1142         }
1143 }
1144
1145
1146 void BufferParams::readGraphicsDriver(LyXLex & lex)
1147 {
1148         if (!lex.next()) return;
1149
1150         string const tmptok = lex.getString();
1151         // check if tmptok is part of tex_graphics in tex_defs.h
1152         int n = 0;
1153         while (true) {
1154                 string const test = tex_graphics[n++];
1155
1156                 if (test == tmptok) {
1157                         graphicsDriver = tmptok;
1158                         break;
1159                 } else if (test == "") {
1160                         lex.printError(
1161                                 "Warning: graphics driver `$$Token' not recognized!\n"
1162                                 "         Setting graphics driver to `default'.\n");
1163                         graphicsDriver = "default";
1164                         break;
1165                 }
1166         }
1167 }
1168
1169
1170 void BufferParams::readBullets(LyXLex & lex)
1171 {
1172         if (!lex.next()) return;
1173
1174         int const index = lex.getInteger();
1175         lex.next();
1176         int temp_int = lex.getInteger();
1177         user_defined_bullet(index).setFont(temp_int);
1178         temp_bullet(index).setFont(temp_int);
1179         lex >> temp_int;
1180         user_defined_bullet(index).setCharacter(temp_int);
1181         temp_bullet(index).setCharacter(temp_int);
1182         lex >> temp_int;
1183         user_defined_bullet(index).setSize(temp_int);
1184         temp_bullet(index).setSize(temp_int);
1185 }
1186
1187
1188 void BufferParams::readBulletsLaTeX(LyXLex & lex)
1189 {
1190         // The bullet class should be able to read this.
1191         if (!lex.next()) return;
1192         int const index = lex.getInteger();
1193         lex.next(true);
1194         string const temp_str = lex.getString();
1195
1196         user_defined_bullet(index).setText(temp_str);
1197         temp_bullet(index).setText(temp_str);
1198 }
1199
1200
1201 string const BufferParams::paperSizeName() const
1202 {
1203         char real_papersize = papersize;
1204         if (real_papersize == PAPER_DEFAULT)
1205                 real_papersize = lyxrc.default_papersize;
1206
1207         switch (real_papersize) {
1208         case PAPER_A3:
1209                 return "a3";
1210         case PAPER_A4:
1211                 return "a4";
1212         case PAPER_A5:
1213                 return "a5";
1214         case PAPER_B5:
1215                 return "b5";
1216         case PAPER_USEXECUTIVE:
1217                 return "foolscap";
1218         case PAPER_USLEGAL:
1219                 return "legal";
1220         case PAPER_USLETTER:
1221         default:
1222                 return "letter";
1223         }
1224 }
1225
1226
1227 string const BufferParams::dvips_options() const
1228 {
1229         string result;
1230
1231         if (use_geometry
1232             && papersize == PAPER_CUSTOM
1233             && !lyxrc.print_paper_dimension_flag.empty()
1234             && !paperwidth.empty()
1235             && !paperheight.empty()) {
1236                 // using a custom papersize
1237                 result = lyxrc.print_paper_dimension_flag;
1238                 result += ' ' + paperwidth;
1239                 result += ',' + paperheight;
1240         } else {
1241                 string const paper_option = paperSizeName();
1242                 if (paper_option != "letter" ||
1243                     orientation != ORIENTATION_LANDSCAPE) {
1244                         // dvips won't accept -t letter -t landscape.
1245                         // In all other cases, include the paper size
1246                         // explicitly.
1247                         result = lyxrc.print_paper_flag;
1248                         result += ' ' + paper_option;
1249                 }
1250         }
1251         if (orientation == ORIENTATION_LANDSCAPE &&
1252             papersize != PAPER_CUSTOM)
1253                 result += ' ' + lyxrc.print_landscape_flag;
1254         return result;
1255 }
1256
1257
1258 string const BufferParams::babelCall(string const & lang_opts) const
1259 {
1260         string tmp = lyxrc.language_package;
1261         if (!lyxrc.language_global_options && tmp == "\\usepackage{babel}")
1262                 tmp = string("\\usepackage[") + lang_opts + "]{babel}";
1263         return tmp;
1264 }