]> git.lyx.org Git - lyx.git/blob - src/TextClass.cpp
forgot that
[lyx.git] / src / TextClass.cpp
1 /**
2  * \file TextClass.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Jean-Marc Lasgouttes
8  * \author Angus Leeming
9  * \author John Levon
10  * \author André Pönitz
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "TextClass.h"
18
19 #include "LayoutFile.h"
20 #include "Color.h"
21 #include "Counters.h"
22 #include "Floating.h"
23 #include "FloatList.h"
24 #include "Layout.h"
25 #include "Lexer.h"
26 #include "Font.h"
27
28 #include "frontends/alert.h"
29
30 #include "support/lassert.h"
31 #include "support/debug.h"
32 #include "support/ExceptionMessage.h"
33 #include "support/FileName.h"
34 #include "support/filetools.h"
35 #include "support/gettext.h"
36 #include "support/lstrings.h"
37 #include "support/os.h"
38
39 #include <algorithm>
40 #include <fstream>
41 #include <sstream>
42
43 using namespace std;
44 using namespace lyx::support;
45
46 namespace lyx {
47
48 namespace {
49
50 class LayoutNamesEqual : public unary_function<Layout, bool> {
51 public:
52         LayoutNamesEqual(docstring const & name)
53                 : name_(name)
54         {}
55         bool operator()(Layout const & c) const
56         {
57                 return c.name() == name_;
58         }
59 private:
60         docstring name_;
61 };
62
63
64 int const FORMAT = 11;
65
66
67 bool layout2layout(FileName const & filename, FileName const & tempfile)
68 {
69         FileName const script = libFileSearch("scripts", "layout2layout.py");
70         if (script.empty()) {
71                 LYXERR0("Could not find layout conversion "
72                           "script layout2layout.py.");
73                 return false;
74         }
75
76         ostringstream command;
77         command << os::python() << ' ' << quoteName(script.toFilesystemEncoding())
78                 << ' ' << quoteName(filename.toFilesystemEncoding())
79                 << ' ' << quoteName(tempfile.toFilesystemEncoding());
80         string const command_str = command.str();
81
82         LYXERR(Debug::TCLASS, "Running `" << command_str << '\'');
83
84         cmd_ret const ret = runCommand(command_str);
85         if (ret.first != 0) {
86                 LYXERR0("Could not run layout conversion script layout2layout.py.");
87                 return false;
88         }
89         return true;
90 }
91
92
93 std::string translateRT(TextClass::ReadType rt) 
94 {
95         switch (rt) {
96         case TextClass::BASECLASS:
97                 return "textclass";
98         case TextClass::MERGE:
99                 return "input file";
100         case TextClass::MODULE:
101                 return "module file";
102         case TextClass::VALIDATION:
103                 return "validation";
104         }
105         // shutup warning
106         return string();
107 }
108
109 } // namespace anon
110
111
112 // This string should not be translated here, 
113 // because it is a layout identifier.
114 docstring const TextClass::plain_layout_ = from_ascii("Plain Layout");
115
116
117 InsetLayout DocumentClass::plain_insetlayout_;
118
119
120 /////////////////////////////////////////////////////////////////////////
121 //
122 // TextClass
123 //
124 /////////////////////////////////////////////////////////////////////////
125
126 TextClass::TextClass()
127 {
128         outputType_ = LATEX;
129         columns_ = 1;
130         sides_ = OneSide;
131         secnumdepth_ = 3;
132         tocdepth_ = 3;
133         pagestyle_ = "default";
134         defaultfont_ = sane_font;
135         opt_fontsize_ = "10|11|12";
136         opt_pagestyle_ = "empty|plain|headings|fancy";
137         titletype_ = TITLE_COMMAND_AFTER;
138         titlename_ = "maketitle";
139         loaded_ = false;
140         _("Plain Layout"); // a hack to make this translatable
141 }
142
143
144 bool TextClass::readStyle(Lexer & lexrc, Layout & lay) const
145 {
146         LYXERR(Debug::TCLASS, "Reading style " << to_utf8(lay.name()));
147         if (!lay.read(lexrc, *this)) {
148                 LYXERR0("Error parsing style `" << to_utf8(lay.name()) << '\'');
149                 return false;
150         }
151         // Resolve fonts
152         lay.resfont = lay.font;
153         lay.resfont.realize(defaultfont_);
154         lay.reslabelfont = lay.labelfont;
155         lay.reslabelfont.realize(defaultfont_);
156         return true; // no errors
157 }
158
159
160 enum TextClassTags {
161         TC_OUTPUTTYPE = 1,
162         TC_INPUT,
163         TC_STYLE,
164         TC_DEFAULTSTYLE,
165         TC_INSETLAYOUT,
166         TC_NOSTYLE,
167         TC_COLUMNS,
168         TC_SIDES,
169         TC_PAGESTYLE,
170         TC_DEFAULTFONT,
171         TC_SECNUMDEPTH,
172         TC_TOCDEPTH,
173         TC_CLASSOPTIONS,
174         TC_PREAMBLE,
175         TC_PROVIDES,
176         TC_REQUIRES,
177         TC_LEFTMARGIN,
178         TC_RIGHTMARGIN,
179         TC_FLOAT,
180         TC_COUNTER,
181         TC_NOFLOAT,
182         TC_TITLELATEXNAME,
183         TC_TITLELATEXTYPE,
184         TC_FORMAT,
185         TC_ADDTOPREAMBLE,
186         TC_DEFAULTMODULE,
187         TC_PROVIDESMODULE,
188         TC_EXCLUDESMODULE
189 };
190
191
192 namespace {
193
194         LexerKeyword textClassTags[] = {
195                 { "addtopreamble",   TC_ADDTOPREAMBLE },
196                 { "classoptions",    TC_CLASSOPTIONS },
197                 { "columns",         TC_COLUMNS },
198                 { "counter",         TC_COUNTER },
199                 { "defaultfont",     TC_DEFAULTFONT },
200                 { "defaultmodule",   TC_DEFAULTMODULE },
201                 { "defaultstyle",    TC_DEFAULTSTYLE },
202                 { "excludesmodule",  TC_EXCLUDESMODULE },
203                 { "float",           TC_FLOAT },
204                 { "format",          TC_FORMAT },
205                 { "input",           TC_INPUT },
206                 { "insetlayout",     TC_INSETLAYOUT },
207                 { "leftmargin",      TC_LEFTMARGIN },
208                 { "nofloat",         TC_NOFLOAT },
209                 { "nostyle",         TC_NOSTYLE },
210                 { "outputtype",      TC_OUTPUTTYPE },
211                 { "pagestyle",       TC_PAGESTYLE },
212                 { "preamble",        TC_PREAMBLE },
213                 { "provides",        TC_PROVIDES },
214                 { "providesmodule",  TC_PROVIDESMODULE },
215                 { "requires",        TC_REQUIRES },
216                 { "rightmargin",     TC_RIGHTMARGIN },
217                 { "secnumdepth",     TC_SECNUMDEPTH },
218                 { "sides",           TC_SIDES },
219                 { "style",           TC_STYLE },
220                 { "titlelatexname",  TC_TITLELATEXNAME },
221                 { "titlelatextype",  TC_TITLELATEXTYPE },
222                 { "tocdepth",        TC_TOCDEPTH }
223         };
224         
225 } //namespace anon
226
227
228 bool TextClass::convertLayoutFormat(support::FileName const & filename, ReadType rt)
229 {
230         LYXERR(Debug::TCLASS, "Converting layout file to " << FORMAT);
231         FileName const tempfile = FileName::tempName("convert_layout");
232         bool success = layout2layout(filename, tempfile);
233         if (success)
234                 success = read(tempfile, rt);
235         tempfile.removeFile();
236         return success;
237 }
238
239 bool TextClass::read(FileName const & filename, ReadType rt)
240 {
241         if (!filename.isReadableFile()) {
242                 lyxerr << "Cannot read layout file `" << filename << "'."
243                        << endl;
244                 return false;
245         }
246
247         LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
248                 to_utf8(makeDisplayPath(filename.absFilename())));
249
250         // Define the plain layout used in table cells, ert, etc. Note that 
251         // we do this before loading any layout file, so that classes can 
252         // override features of this layout if they should choose to do so.
253         if (rt == BASECLASS && !hasLayout(plain_layout_))
254                 layoutlist_.push_back(createBasicLayout(plain_layout_));
255
256         Lexer lexrc(textClassTags);
257         lexrc.setFile(filename);
258         ReturnValues retval = read(lexrc, rt);
259         
260         LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
261                         to_utf8(makeDisplayPath(filename.absFilename())));
262         
263         if (retval != FORMAT_MISMATCH) 
264                 return retval == OK;
265         
266         bool const worx = convertLayoutFormat(filename, rt);
267         if (!worx) {
268                 LYXERR0 ("Unable to convert " << filename << 
269                         " to format " << FORMAT);
270                 return false;
271         }
272         return true;
273 }
274
275
276 bool TextClass::validate(std::string const & str)
277 {
278         TextClass tc;
279         return tc.read(str, VALIDATION);
280 }
281
282
283 bool TextClass::read(std::string const & str, ReadType rt) 
284 {
285         Lexer lexrc(textClassTags);
286         istringstream is(str);
287         lexrc.setStream(is);
288         ReturnValues retval = read(lexrc, rt);
289
290         if (retval != FORMAT_MISMATCH) 
291                 return retval == OK;
292
293         // write the layout string to a temporary file
294         FileName const tempfile = FileName::tempName("TextClass_read");
295         ofstream os(tempfile.toFilesystemEncoding().c_str());
296         if (!os) {
297                 LYXERR0("Unable to create temporary file");
298                 return false;
299         }
300         os << str;
301         os.close();
302
303         // now try to convert it
304         bool const worx = convertLayoutFormat(tempfile, rt);
305         if (!worx) {
306                 LYXERR0("Unable to convert internal layout information to format " 
307                         << FORMAT);
308         }
309         tempfile.removeFile();
310         return worx;
311 }
312
313
314 // Reads a textclass structure from file.
315 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt) 
316 {
317         bool error = !lexrc.isOK();
318
319         // Format of files before the 'Format' tag was introduced
320         int format = 1;
321
322         // parsing
323         while (lexrc.isOK() && !error) {
324                 int le = lexrc.lex();
325
326                 switch (le) {
327                 case Lexer::LEX_FEOF:
328                         continue;
329
330                 case Lexer::LEX_UNDEF:
331                         lexrc.printError("Unknown TextClass tag `$$Token'");
332                         error = true;
333                         continue;
334
335                 default:
336                         break;
337                 }
338
339                 switch (static_cast<TextClassTags>(le)) {
340
341                 case TC_FORMAT:
342                         if (lexrc.next())
343                                 format = lexrc.getInteger();
344                         break;
345
346                 case TC_OUTPUTTYPE:   // output type definition
347                         readOutputType(lexrc);
348                         break;
349
350                 case TC_INPUT: // Include file
351                         if (lexrc.next()) {
352                                 string const inc = lexrc.getString();
353                                 FileName tmp = libFileSearch("layouts", inc,
354                                                             "layout");
355
356                                 if (tmp.empty()) {
357                                         lexrc.printError("Could not find input file: " + inc);
358                                         error = true;
359                                 } else if (!read(tmp, MERGE)) {
360                                         lexrc.printError("Error reading input"
361                                                          "file: " + tmp.absFilename());
362                                         error = true;
363                                 }
364                         }
365                         break;
366
367                 case TC_DEFAULTSTYLE:
368                         if (lexrc.next()) {
369                                 docstring const name = from_utf8(subst(lexrc.getString(),
370                                                           '_', ' '));
371                                 defaultlayout_ = name;
372                         }
373                         break;
374
375                 case TC_STYLE:
376                         if (lexrc.next()) {
377                                 docstring const name = from_utf8(subst(lexrc.getString(),
378                                                     '_', ' '));
379                                 if (name.empty()) {
380                                         string s = "Could not read name for style: `$$Token' "
381                                                 + lexrc.getString() + " is probably not valid UTF-8!";
382                                         lexrc.printError(s.c_str());
383                                         Layout lay;
384                                         // Since we couldn't read the name, we just scan the rest
385                                         // of the style and discard it.
386                                         error = !readStyle(lexrc, lay);
387                                 } else if (hasLayout(name)) {
388                                         Layout & lay = operator[](name);
389                                         error = !readStyle(lexrc, lay);
390                                 } else {
391                                         Layout layout;
392                                         layout.setName(name);
393                                         error = !readStyle(lexrc, layout);
394                                         if (!error)
395                                                 layoutlist_.push_back(layout);
396
397                                         if (defaultlayout_.empty()) {
398                                                 // We do not have a default layout yet, so we choose
399                                                 // the first layout we encounter.
400                                                 defaultlayout_ = name;
401                                         }
402                                 }
403                         }
404                         else {
405                                 lexrc.printError("No name given for style: `$$Token'.");
406                                 error = true;
407                         }
408                         break;
409
410                 case TC_NOSTYLE:
411                         if (lexrc.next()) {
412                                 docstring const style = from_utf8(subst(lexrc.getString(),
413                                                      '_', ' '));
414                                 if (!deleteLayout(style))
415                                         lyxerr << "Cannot delete style `"
416                                                << to_utf8(style) << '\'' << endl;
417                         }
418                         break;
419
420                 case TC_COLUMNS:
421                         if (lexrc.next())
422                                 columns_ = lexrc.getInteger();
423                         break;
424
425                 case TC_SIDES:
426                         if (lexrc.next()) {
427                                 switch (lexrc.getInteger()) {
428                                 case 1: sides_ = OneSide; break;
429                                 case 2: sides_ = TwoSides; break;
430                                 default:
431                                         lyxerr << "Impossible number of page"
432                                                 " sides, setting to one."
433                                                << endl;
434                                         sides_ = OneSide;
435                                         break;
436                                 }
437                         }
438                         break;
439
440                 case TC_PAGESTYLE:
441                         lexrc.next();
442                         pagestyle_ = rtrim(lexrc.getString());
443                         break;
444
445                 case TC_DEFAULTFONT:
446                         defaultfont_ = lyxRead(lexrc);
447                         if (!defaultfont_.resolved()) {
448                                 lexrc.printError("Warning: defaultfont should "
449                                                  "be fully instantiated!");
450                                 defaultfont_.realize(sane_font);
451                         }
452                         break;
453
454                 case TC_SECNUMDEPTH:
455                         lexrc.next();
456                         secnumdepth_ = lexrc.getInteger();
457                         break;
458
459                 case TC_TOCDEPTH:
460                         lexrc.next();
461                         tocdepth_ = lexrc.getInteger();
462                         break;
463
464                 // First step to support options
465                 case TC_CLASSOPTIONS:
466                         readClassOptions(lexrc);
467                         break;
468
469                 case TC_PREAMBLE:
470                         preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
471                         break;
472
473                 case TC_ADDTOPREAMBLE:
474                         preamble_ += from_utf8(lexrc.getLongString("EndPreamble"));
475                         break;
476
477                 case TC_PROVIDES: {
478                         lexrc.next();
479                         string const feature = lexrc.getString();
480                         lexrc.next();
481                         if (lexrc.getInteger())
482                                 provides_.insert(feature);
483                         else
484                                 provides_.erase(feature);
485                         break;
486                 }
487
488                 case TC_REQUIRES: {
489                         lexrc.eatLine();
490                         vector<string> const req 
491                                 = getVectorFromString(lexrc.getString());
492                         requires_.insert(req.begin(), req.end());
493                         break;
494                 }
495
496                 case TC_DEFAULTMODULE: {
497                         lexrc.next();
498                         string const module = lexrc.getString();
499                         if (find(default_modules_.begin(), default_modules_.end(), module) == default_modules_.end())
500                                 default_modules_.push_back(module);
501                         break;
502                 }
503
504                 case TC_PROVIDESMODULE: {
505                         lexrc.next();
506                         string const module = lexrc.getString();
507                         if (find(provided_modules_.begin(), provided_modules_.end(), module) == provided_modules_.end())
508                                 provided_modules_.push_back(module);
509                         break;
510                 }
511
512                 case TC_EXCLUDESMODULE: {
513                         lexrc.next();
514                         string const module = lexrc.getString();
515                         // modules already have their own way to exclude other modules
516                         if (rt == MODULE) {
517                                 LYXERR0("ExcludesModule tag cannot be used in a module!");
518                                 break;
519                         }
520                         if (find(excluded_modules_.begin(), excluded_modules_.end(), module) == excluded_modules_.end())
521                                 excluded_modules_.push_back(module);
522                         break;
523                 }
524
525                 case TC_LEFTMARGIN:     // left margin type
526                         if (lexrc.next())
527                                 leftmargin_ = lexrc.getDocString();
528                         break;
529
530                 case TC_RIGHTMARGIN:    // right margin type
531                         if (lexrc.next())
532                                 rightmargin_ = lexrc.getDocString();
533                         break;
534
535                 case TC_INSETLAYOUT:
536                         if (lexrc.next()) {
537                                 InsetLayout il;
538                                 if (il.read(lexrc, *this))
539                                         insetlayoutlist_[il.name()] = il;
540                                 // else there was an error, so forget it
541                         }
542                         break;
543
544                 case TC_FLOAT:
545                         readFloat(lexrc);
546                         break;
547
548                 case TC_COUNTER:
549                         if (lexrc.next()) {
550                                 docstring const name = lexrc.getDocString();
551                                 if (name.empty()) {
552                                         string s = "Could not read name for counter: `$$Token' "
553                                                         + lexrc.getString() + " is probably not valid UTF-8!";
554                                         lexrc.printError(s.c_str());
555                                         Counter c;
556                                         // Since we couldn't read the name, we just scan the rest
557                                         // and discard it.
558                                         c.read(lexrc);
559                                 } else
560                                         error = !counters_.read(lexrc, name);
561                         }
562                         else {
563                                 lexrc.printError("No name given for style: `$$Token'.");
564                                 error = true;
565                         }
566                         break;
567
568                 case TC_TITLELATEXTYPE:
569                         readTitleType(lexrc);
570                         break;
571
572                 case TC_TITLELATEXNAME:
573                         if (lexrc.next())
574                                 titlename_ = lexrc.getString();
575                         break;
576
577                 case TC_NOFLOAT:
578                         if (lexrc.next()) {
579                                 string const nofloat = lexrc.getString();
580                                 floatlist_.erase(nofloat);
581                         }
582                         break;
583                 } // end of switch
584
585                 //Note that this is triggered the first time through the loop unless
586                 //we hit a format tag.
587                 if (format != FORMAT)
588                         break;
589         }
590
591         if (format != FORMAT)
592                 return FORMAT_MISMATCH;
593
594         if (rt != BASECLASS) 
595                 return (error ? ERROR : OK);
596
597         if (defaultlayout_.empty()) {
598                 LYXERR0("Error: Textclass '" << name_
599                                                 << "' is missing a defaultstyle.");
600                 error = true;
601         }
602                 
603         // Try to erase "stdinsets" from the provides_ set. 
604         // The
605         //   Provides stdinsets 1
606         // declaration simply tells us that the standard insets have been
607         // defined. (It's found in stdinsets.inc but could also be used in
608         // user-defined files.) There isn't really any such package. So we
609         // might as well go ahead and erase it.
610         // If we do not succeed, then it was not there, which means that
611         // the textclass did not provide the definitions of the standard
612         // insets. So we need to try to load them.
613         int erased = provides_.erase("stdinsets");
614         if (!erased) {
615                 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
616
617                 if (tmp.empty()) {
618                         throw ExceptionMessage(WarningException, _("Missing File"),
619                                 _("Could not find stdinsets.inc! This may lead to data loss!"));
620                         error = true;
621                 } else if (!read(tmp, MERGE)) {
622                         throw ExceptionMessage(WarningException, _("Corrupt File"),
623                                 _("Could not read stdinsets.inc! This may lead to data loss!"));
624                         error = true;
625                 }
626         }
627
628         min_toclevel_ = Layout::NOT_IN_TOC;
629         max_toclevel_ = Layout::NOT_IN_TOC;
630         const_iterator lit = begin();
631         const_iterator len = end();
632         for (; lit != len; ++lit) {
633                 int const toclevel = lit->toclevel;
634                 if (toclevel != Layout::NOT_IN_TOC) {
635                         if (min_toclevel_ == Layout::NOT_IN_TOC)
636                                 min_toclevel_ = toclevel;
637                         else
638                                 min_toclevel_ = min(min_toclevel_, toclevel);
639                         max_toclevel_ = max(max_toclevel_, toclevel);
640                 }
641         }
642         LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
643                 << ", maximum is " << max_toclevel_);
644
645         return (error ? ERROR : OK);
646 }
647
648
649 void TextClass::readTitleType(Lexer & lexrc)
650 {
651         LexerKeyword titleTypeTags[] = {
652                 { "commandafter", TITLE_COMMAND_AFTER },
653                 { "environment",  TITLE_ENVIRONMENT }
654         };
655
656         PushPopHelper pph(lexrc, titleTypeTags);
657
658         int le = lexrc.lex();
659         switch (le) {
660         case Lexer::LEX_UNDEF:
661                 lexrc.printError("Unknown output type `$$Token'");
662                 break;
663         case TITLE_COMMAND_AFTER:
664         case TITLE_ENVIRONMENT:
665                 titletype_ = static_cast<TitleLatexType>(le);
666                 break;
667         default:
668                 LYXERR0("Unhandled value " << le << " in TextClass::readTitleType.");
669                 break;
670         }
671 }
672
673
674 void TextClass::readOutputType(Lexer & lexrc)
675 {
676         LexerKeyword outputTypeTags[] = {
677                 { "docbook",  DOCBOOK },
678                 { "latex",    LATEX },
679                 { "literate", LITERATE }
680         };
681
682         PushPopHelper pph(lexrc, outputTypeTags);
683
684         int le = lexrc.lex();
685         switch (le) {
686         case Lexer::LEX_UNDEF:
687                 lexrc.printError("Unknown output type `$$Token'");
688                 return;
689         case LATEX:
690         case DOCBOOK:
691         case LITERATE:
692                 outputType_ = static_cast<OutputType>(le);
693                 break;
694         default:
695                 LYXERR0("Unhandled value " << le);
696                 break;
697         }
698 }
699
700
701 void TextClass::readClassOptions(Lexer & lexrc)
702 {
703         enum {
704                 CO_FONTSIZE = 1,
705                 CO_PAGESTYLE,
706                 CO_OTHER,
707                 CO_HEADER,
708                 CO_END
709         };
710
711         LexerKeyword classOptionsTags[] = {
712                 {"end",       CO_END },
713                 {"fontsize",  CO_FONTSIZE },
714                 {"header",    CO_HEADER },
715                 {"other",     CO_OTHER },
716                 {"pagestyle", CO_PAGESTYLE }
717         };
718
719         lexrc.pushTable(classOptionsTags);
720         bool getout = false;
721         while (!getout && lexrc.isOK()) {
722                 int le = lexrc.lex();
723                 switch (le) {
724                 case Lexer::LEX_UNDEF:
725                         lexrc.printError("Unknown ClassOption tag `$$Token'");
726                         continue;
727                 default: break;
728                 }
729                 switch (le) {
730                 case CO_FONTSIZE:
731                         lexrc.next();
732                         opt_fontsize_ = rtrim(lexrc.getString());
733                         break;
734                 case CO_PAGESTYLE:
735                         lexrc.next();
736                         opt_pagestyle_ = rtrim(lexrc.getString());
737                         break;
738                 case CO_OTHER:
739                         lexrc.next();
740                         options_ = lexrc.getString();
741                         break;
742                 case CO_HEADER:
743                         lexrc.next();
744                         class_header_ = subst(lexrc.getString(), "&quot;", "\"");
745                         break;
746                 case CO_END:
747                         getout = true;
748                         break;
749                 }
750         }
751         lexrc.popTable();
752 }
753
754
755 void TextClass::readFloat(Lexer & lexrc)
756 {
757         enum {
758                 FT_TYPE = 1,
759                 FT_NAME,
760                 FT_PLACEMENT,
761                 FT_EXT,
762                 FT_WITHIN,
763                 FT_STYLE,
764                 FT_LISTNAME,
765                 FT_BUILTIN,
766                 FT_END
767         };
768
769         LexerKeyword floatTags[] = {
770                 { "end", FT_END },
771                 { "extension", FT_EXT },
772                 { "guiname", FT_NAME },
773                 { "latexbuiltin", FT_BUILTIN },
774                 { "listname", FT_LISTNAME },
775                 { "numberwithin", FT_WITHIN },
776                 { "placement", FT_PLACEMENT },
777                 { "style", FT_STYLE },
778                 { "type", FT_TYPE }
779         };
780
781         lexrc.pushTable(floatTags);
782
783         string type;
784         string placement;
785         string ext;
786         string within;
787         string style;
788         string name;
789         string listName;
790         bool builtin = false;
791
792         bool getout = false;
793         while (!getout && lexrc.isOK()) {
794                 int le = lexrc.lex();
795                 switch (le) {
796                 case Lexer::LEX_UNDEF:
797                         lexrc.printError("Unknown float tag `$$Token'");
798                         continue;
799                 default: break;
800                 }
801                 switch (le) {
802                 case FT_TYPE:
803                         lexrc.next();
804                         type = lexrc.getString();
805                         if (floatlist_.typeExist(type)) {
806                                 Floating const & fl = floatlist_.getType(type);
807                                 placement = fl.placement();
808                                 ext = fl.ext();
809                                 within = fl.within();
810                                 style = fl.style();
811                                 name = fl.name();
812                                 listName = fl.listName();
813                                 builtin = fl.builtin();
814                         } 
815                         break;
816                 case FT_NAME:
817                         lexrc.next();
818                         name = lexrc.getString();
819                         break;
820                 case FT_PLACEMENT:
821                         lexrc.next();
822                         placement = lexrc.getString();
823                         break;
824                 case FT_EXT:
825                         lexrc.next();
826                         ext = lexrc.getString();
827                         break;
828                 case FT_WITHIN:
829                         lexrc.next();
830                         within = lexrc.getString();
831                         if (within == "none")
832                                 within.erase();
833                         break;
834                 case FT_STYLE:
835                         lexrc.next();
836                         style = lexrc.getString();
837                         break;
838                 case FT_LISTNAME:
839                         lexrc.next();
840                         listName = lexrc.getString();
841                         break;
842                 case FT_BUILTIN:
843                         lexrc.next();
844                         builtin = lexrc.getBool();
845                         break;
846                 case FT_END:
847                         getout = true;
848                         break;
849                 }
850         }
851
852         // Here if have a full float if getout == true
853         if (getout) {
854                 Floating fl(type, placement, ext, within,
855                             style, name, listName, builtin);
856                 floatlist_.newFloat(fl);
857                 // each float has its own counter
858                 counters_.newCounter(from_ascii(type), from_ascii(within),
859                                       docstring(), docstring());
860                 // also define sub-float counters
861                 docstring const subtype = "sub-" + from_ascii(type);
862                 counters_.newCounter(subtype, from_ascii(type),
863                                       "\\alph{" + subtype + "}", docstring());
864         }
865
866         lexrc.popTable();
867 }
868
869
870 bool TextClass::hasLayout(docstring const & n) const
871 {
872         docstring const name = n.empty() ? defaultLayoutName() : n;
873
874         return find_if(layoutlist_.begin(), layoutlist_.end(),
875                        LayoutNamesEqual(name))
876                 != layoutlist_.end();
877 }
878
879
880 Layout const & TextClass::operator[](docstring const & name) const
881 {
882         LASSERT(!name.empty(), /**/);
883
884         const_iterator it = 
885                 find_if(begin(), end(), LayoutNamesEqual(name));
886
887         if (it == end()) {
888                 lyxerr << "We failed to find the layout '" << to_utf8(name)
889                        << "' in the layout list. You MUST investigate!"
890                        << endl;
891                 for (const_iterator cit = begin(); cit != end(); ++cit)
892                         lyxerr  << " " << to_utf8(cit->name()) << endl;
893
894                 // we require the name to exist
895                 LASSERT(false, /**/);
896         }
897
898         return *it;
899 }
900
901
902 Layout & TextClass::operator[](docstring const & name)
903 {
904         LASSERT(!name.empty(), /**/);
905
906         iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
907
908         if (it == end()) {
909                 LYXERR0("We failed to find the layout '" << to_utf8(name)
910                        << "' in the layout list. You MUST investigate!");
911                 for (const_iterator cit = begin(); cit != end(); ++cit)
912                         LYXERR0(" " << to_utf8(cit->name()));
913
914                 // we require the name to exist
915                 LASSERT(false, /**/);
916         }
917
918         return *it;
919 }
920
921
922 bool TextClass::deleteLayout(docstring const & name)
923 {
924         if (name == defaultLayoutName() || name == plainLayoutName())
925                 return false;
926
927         LayoutList::iterator it =
928                 remove_if(layoutlist_.begin(), layoutlist_.end(),
929                           LayoutNamesEqual(name));
930
931         LayoutList::iterator end = layoutlist_.end();
932         bool const ret = (it != end);
933         layoutlist_.erase(it, end);
934         return ret;
935 }
936
937
938 // Load textclass info if not loaded yet
939 bool TextClass::load(string const & path) const
940 {
941         if (loaded_)
942                 return true;
943
944         // Read style-file, provided path is searched before the system ones
945         // If path is a file, it is loaded directly.
946         FileName layout_file(path);
947         if (!path.empty() && !layout_file.isReadableFile())
948                 layout_file = FileName(addName(path, name_ + ".layout"));
949         if (layout_file.empty() || !layout_file.exists())
950                 layout_file = libFileSearch("layouts", name_, "layout");
951         loaded_ = const_cast<TextClass*>(this)->read(layout_file);
952
953         if (!loaded_) {
954                 lyxerr << "Error reading `"
955                        << to_utf8(makeDisplayPath(layout_file.absFilename()))
956                        << "'\n(Check `" << name_
957                        << "')\nCheck your installation and "
958                         "try Options/Reconfigure..." << endl;
959         }
960
961         return loaded_;
962 }
963
964
965 void DocumentClass::addLayoutIfNeeded(docstring const & n) const
966 {
967         if (!hasLayout(n))
968                 layoutlist_.push_back(createBasicLayout(n, true));
969 }
970
971
972 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const 
973 {
974         // FIXME The fix for the InsetLayout part of 4812 would be here:
975         // Add the InsetLayout to the document class if it is not found.
976         docstring n = name;
977         InsetLayouts::const_iterator cen = insetlayoutlist_.end();
978         while (!n.empty()) {
979                 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
980                 if (cit != cen && cit->first == n)
981                         return cit->second;
982                 size_t i = n.find(':');
983                 if (i == string::npos)
984                         break;
985                 n = n.substr(0, i);
986         }
987         return plain_insetlayout_;
988 }
989
990
991 docstring const & TextClass::defaultLayoutName() const
992 {
993         // This really should come from the actual layout... (Lgb)
994         return defaultlayout_;
995 }
996
997
998 Layout const & TextClass::defaultLayout() const
999 {
1000         return operator[](defaultLayoutName());
1001 }
1002
1003
1004 bool TextClass::isDefaultLayout(Layout const & layout) const 
1005 {
1006         return layout.name() == defaultLayoutName();
1007 }
1008
1009
1010 bool TextClass::isPlainLayout(Layout const & layout) const 
1011 {
1012         return layout.name() == plainLayoutName();
1013 }
1014
1015
1016 Layout TextClass::createBasicLayout(docstring const & name, bool unknown) const
1017 {
1018         static Layout * defaultLayout = NULL;
1019
1020         if (defaultLayout) {
1021                 defaultLayout->setUnknown(unknown);
1022                 defaultLayout->setName(name);
1023                 return *defaultLayout;
1024         }
1025
1026         static char const * s = "Margin Static\n"
1027                         "LatexType Paragraph\n"
1028                         "LatexName dummy\n"
1029                         "Align Block\n"
1030                         "AlignPossible Left, Right, Center\n"
1031                         "LabelType No_Label\n"
1032                         "End";
1033         istringstream ss(s);
1034         Lexer lex(textClassTags);
1035         lex.setStream(ss);
1036         defaultLayout = new Layout;
1037         defaultLayout->setUnknown(unknown);
1038         defaultLayout->setName(name);
1039         if (!readStyle(lex, *defaultLayout)) {
1040                 // The only way this happens is because the hardcoded layout above
1041                 // is wrong.
1042                 LASSERT(false, /**/);
1043         };
1044         return *defaultLayout;
1045 }
1046
1047 /////////////////////////////////////////////////////////////////////////
1048 //
1049 // DocumentClassBundle
1050 //
1051 /////////////////////////////////////////////////////////////////////////
1052
1053 DocumentClassBundle::~DocumentClassBundle()
1054 {
1055         for (size_t i = 0; i != documentClasses_.size(); ++i)
1056                 delete documentClasses_[i];
1057         documentClasses_.clear();
1058 }
1059
1060 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1061 {
1062         DocumentClass * dc = new DocumentClass(baseClass);
1063         documentClasses_.push_back(dc);
1064         return *documentClasses_.back();
1065 }
1066
1067
1068 DocumentClassBundle & DocumentClassBundle::get()
1069 {
1070         static DocumentClassBundle singleton; 
1071         return singleton; 
1072 }
1073
1074
1075 /////////////////////////////////////////////////////////////////////////
1076 //
1077 // DocumentClass
1078 //
1079 /////////////////////////////////////////////////////////////////////////
1080
1081 DocumentClass::DocumentClass(LayoutFile const & tc)
1082         : TextClass(tc)
1083 {}
1084
1085
1086 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1087 {
1088         LayoutList::const_iterator it  = layoutlist_.begin();
1089         LayoutList::const_iterator end = layoutlist_.end();
1090         for (; it != end; ++it)
1091                 if (it->latexname() == lay)
1092                         return true;
1093         return false;
1094 }
1095
1096
1097 bool DocumentClass::provides(string const & p) const
1098 {
1099         return provides_.find(p) != provides_.end();
1100 }
1101
1102
1103 bool DocumentClass::hasTocLevels() const
1104 {
1105         return min_toclevel_ != Layout::NOT_IN_TOC;
1106 }
1107
1108
1109 /////////////////////////////////////////////////////////////////////////
1110 //
1111 // PageSides
1112 //
1113 /////////////////////////////////////////////////////////////////////////
1114
1115 ostream & operator<<(ostream & os, PageSides p)
1116 {
1117         switch (p) {
1118         case OneSide:
1119                 os << '1';
1120                 break;
1121         case TwoSides:
1122                 os << '2';
1123                 break;
1124         }
1125         return os;
1126 }
1127
1128
1129 } // namespace lyx