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